所以我有一个汽车类和一个汽车测试员类。这是汽车类:
package main;
public class Car {
private long distance;
private double newDistance;
private double gasAmount;
private double newGasAmount;
// Contrsuctor
Car(){
distance = 0;
}
Car(long newDistance){
distance = newDistance;
}
//Accessor
public long getDistance(){
return distance;
}
public double getGasInTank(){
return gasAmount;
}
//Mutator
public void drive(double distance){
newDistance = distance;
}
public void addGas(double gasAmount){
newGasAmount = gasAmount;
}
}
这就是问题所在。在我的carTester类中,为什么myVehicle.drive();
没有工作?
它用红色(netBeans)强调它,并说“包myVehicle不存在”
package main;
public class CarTester {
Car myVehicle = new Car();
myVehicle.drive();
double gasLeft = myVehicle.getGasInTank();
}
答案 0 :(得分:2)
当您尝试在类块中的Object
上调用操作时,编译器将发出此消息。
您需要在main
中使用CarTester
方法。您还需要根据double
方法提供distance
drive
值。
public class CarTester {
public final static void main(String[] args) {
Car myVehicle = new Car();
myVehicle.drive(33.2);
...
}
}
答案 1 :(得分:0)
在方法内的CarTester类中运行代码。例如public final static void main(String [] args){...} ...
e.g。
package main;
public class CarTester {
public final static void main(String[] args) {
Car myVehicle = new Car();
myVehicle.drive();
double gasLeft = myVehicle.getGasInTank();
}
}
答案 2 :(得分:0)
我认为问题是在课程CarTester
中您没有方法。编译器抱怨它找不到名为myVehicle
的包,因为它试图将行myVehicle.drive();
解释为类型。您需要将班级CarTester
更改为:
public class CarTester
{
public static void main(string[] args)
{
Car car = new Car();
car.drive(10.0);
double gasLeft = car.getGasInTank();
}
}