我的代码找不到我已经声明的数组
My code cannot find an array that I have already declared
这是我的代码。当我试图将对象 newCar
放入汽车数组时,问题出现在 for
循环中。它说 Car[]
无法解析为变量,即使我在代码的第四行声明了它。
public class Race {
public double distance;
public String raceType;
public Car[] carsEntered = new Car[3];
final int DEFAULT_NUMBER_OF_CARS = 3;
public static void main(String[] args) {
int carCount = 0;
String winner;
Car myCar = new Car("Chase", 75);
Car ProfCar = new Car("Prof. Harms", 85);
Car JeffCar = new Car("Jeff Gordan", 100);
}
public void changeDistace(double newDistance) {
distance = newDistance;
}
public void changeRaceType(String newRaceType) {
raceType = newRaceType;
}
public void addCar(Car newCar) {
boolean carPlaced = false;
for (int i=0; i < DEFAULT_NUMBER_OF_CARS; i++) {
if (carPlaced == false) {
if (Car[i] == null) {
Car[i] = newCar;
carPlaced = true;
}
}
}
}
}
注意:这不是项目中唯一的 .java 文件。汽车对象已声明并且在我的其他代码中工作正常,我只需要知道为什么我声明的这个数组 (Car[]
) 在 addCar()
的 for
循环中无法识别.
Car[]
是变量的类型,不是名字。变量名为 carsEntered
.
这是我的代码。当我试图将对象 newCar
放入汽车数组时,问题出现在 for
循环中。它说 Car[]
无法解析为变量,即使我在代码的第四行声明了它。
public class Race {
public double distance;
public String raceType;
public Car[] carsEntered = new Car[3];
final int DEFAULT_NUMBER_OF_CARS = 3;
public static void main(String[] args) {
int carCount = 0;
String winner;
Car myCar = new Car("Chase", 75);
Car ProfCar = new Car("Prof. Harms", 85);
Car JeffCar = new Car("Jeff Gordan", 100);
}
public void changeDistace(double newDistance) {
distance = newDistance;
}
public void changeRaceType(String newRaceType) {
raceType = newRaceType;
}
public void addCar(Car newCar) {
boolean carPlaced = false;
for (int i=0; i < DEFAULT_NUMBER_OF_CARS; i++) {
if (carPlaced == false) {
if (Car[i] == null) {
Car[i] = newCar;
carPlaced = true;
}
}
}
}
}
注意:这不是项目中唯一的 .java 文件。汽车对象已声明并且在我的其他代码中工作正常,我只需要知道为什么我声明的这个数组 (Car[]
) 在 addCar()
的 for
循环中无法识别.
Car[]
是变量的类型,不是名字。变量名为 carsEntered
.