由于某种原因,我无法从我的主类中的其他方法访问我在程序的main方法中创建的arrayList。
public static void main(String[] args) {
//creating array list for vehicles
ArrayList<motorVehicle> vehicleList = new ArrayList<motorVehicle>();
getAndCheckMainSelection();
在我的对象输入集合结束时,我去创建和添加值,它在netbeans中给出了一个错误,表示无法找到变量突出显示vehicleList ..
vehicleList.add(new car(wheels, engineSize, valueOfPS, date, serialNumber, doors, color));
答案 0 :(得分:3)
vehicleList
是局部变量,只能在声明它们的方法中访问局部变量,如果要在另一个方法中使用vehicleList
,则应将其声明为实例变量,类变量或传递它作为参数。您可以在docs
答案 1 :(得分:0)
我认为你希望你的arrayList对所有方法都可见。在这种情况下。像这样使用它:
public class Myclass {
private static ArrayList<motorVehicle> vehicleList = new ArrayList<motorVehicle>(); //has to be static to be accessed in static methods
public static void main(String[] args) {
//Do your stuff
getAndCheckMainSelection();
}
如您所见,我将vehicleList声明为私有。这意味着它可以在任何地方使用,但仅限于此类!
答案 2 :(得分:0)
您正在尝试将数据(条目)添加到仅存在于void
主类中的变量中。使vehicleList
变量存在于类Scope
中,以便所有方法都可以访问它(静态旁边)