You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java求助:如何将ControllerRoute对象传入方法并当作数组使用?

问题分析与修复方案

错误根源

你在UpdateAndDelete类里把ControllerRoute对象直接当成数组操作了,但实际上数组是ControllerRoute类内部的routes成员变量,不能直接通过cr.length或cr[i]访问。另外Route类的id是私有成员,缺少对应的getter方法,导致无法读取id值。


1. 修正UpdateAndDelete类代码

要通过cr.routes访问内部的数组,同时补全更新逻辑,还要注意空指针判断(数组元素可能未初始化):

import javax.swing.JOptionPane;
public class UpdateAndDelete{

   public Route updateRoutes(int id, ControllerRoute cr){
      int pos = -1;
      String nwname;
      // 遍历ControllerRoute内部的routes数组
      for(int i=0; i<cr.routes.length; i++){
           // 先判断元素非空,避免空指针异常
           if(cr.routes[i] != null && id == cr.routes[i].getId()){
            pos = i;
            break; // 找到目标后终止遍历,提升效率
           }
      }
      // 找到对应id的路由才执行更新
      if(pos != -1){
          nwname = JOptionPane.showInputDialog(null,"Enter new route name");
          cr.routes[pos] = new Route(id, nwname);
          return cr.routes[pos];
      } else {
          JOptionPane.showMessageDialog(null, "Route not found");
          return null;
      }
   }
}

2. 给Route类添加Getter方法

由于id是私有成员,外部类无法直接访问,必须添加getId()方法:

public class Route{
   private int id;
   private String name;
   
   public Route () {}
   
   public Route(int id, String name){
      this.id = id;
      this.name = name;
   }

   // 提供id的访问方法
   public int getId() {
       return this.id;
   }

   // 可选:添加name的访问方法
   public String getName() {
       return this.name;
   }
}

3. 移除不必要的继承(可选但重要)

ControllerRoute继承Menu会造成循环依赖(Menu实例化ControllerRoute,ControllerRoute又继承Menu),会引发初始化异常。如果ControllerRoute不需要Menu的功能,直接去掉继承:

public class ControllerRoute{
   Route[] routes;
   
   public ControllerRoute(int size){
      routes = new Route[size];
   }
}

内容的提问来源于stack exchange,提问作者HIk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:15:36