简体   繁体   English

Java主要方法中的调用方法

[英]invoking method in main method in Java

I have a question regarding to using method in main class, here is my code for a Race class: 我有一个关于在主类中使用方法的问题,这是我的Race类代码:

import java.util.ArrayList;


public class Race {

    private ArrayList<Car>cars;


    public Race(){
         cars = new ArrayList<Car>();
    }

    public void addCars(Car car){
        cars.add(car);
    }
}

The above is what I have done to make an arraylist for the cars that I am ready to put in by using a main method in another class: 上面是我通过使用另一个类中的main方法为要准备放入的汽车创建数组列表的工作:

public class Test {

    public static void main(String[] args) {
        Car toyota = new Car("Toyota",1.0,1.0,2.0,2.0);
        cars.addCars(toyota);
    }
}

However, it has error in the last line, it shows "cars cannot be resolved",I am not sure how should I fix it, maybe writing a getter method in the Race class? 但是,它在最后一行有错误,显示“无法解决汽车”,我不确定该如何解决,也许在Race类中编写了一个吸气剂方法?

Create an instance of race and call addCars 创建race的实例并调用addCars

Race race = new Race();
race.addCars(toyota);

cars does not exist in that context, you might want to stick to the convention on having lowercase variable names, as well. cars在这种情况下不存在,您可能还想在使用小写变量名称时遵循约定

Change your Test class to something similar to this: 将您的Test类更改为类似以下内容:

public class Test {
    public static void main(String[] args) {
        Race race = new Race();
        Car toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
        race.addCars(toyota);
    }
}

You want to add cars to the race , not cars (which does not exist). 您想将汽车添加到比赛中 ,而不是cars (不存在)。 To add cars to a race, you first need to make one. 要为赛车添加赛车,您首先需要制造一辆。

By adding cars to the race, it will internally add it to the cars list. 通过将汽车添加到比赛中,它将在内部将其添加到汽车列表中。 (Because you made it so) You problem is basically that you are trying to use a variable that is outside the scope. (因为这样做了)您的问题基本上是您试图使用范围之外的变量。 (Somewhere else, basically) (基本上在其他地方)

Since I don't know your exact problem, I can't really help you further, but you might want to save the race in a field rather than a local variable, it all depends on what you want to do. 由于我不知道您的确切问题,因此我无法真正为您提供进一步的帮助,但是您可能希望将比赛保存在字段中,而不是在本地变量中保存,这完全取决于您要执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM