0

所以我有一个汽车班和一个汽车测试员班。这是汽车类:

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();
}
4

3 回答 3

2

当您尝试对Object类块中的 an 调用操作时,编译器将发出此消息。

您需要main使用CarTester. 您还需要double distance根据您的方法提供一个值drive

public class CarTester {
  public final static void main(String[] args) {
    Car myVehicle = new Car();
    myVehicle.drive(33.2);
    ...
  }
}
于 2013-03-27T23:23:49.073 回答
0

在方法内部的 CarTester 类中运行您的代码。例如 public final static void main(String[] args) {...}...

例如

package main;

public class CarTester {
  public final static void main(String[] args) {
    Car myVehicle = new Car();
    myVehicle.drive();
    double gasLeft = myVehicle.getGasInTank();
  }
}
于 2013-03-27T23:25:40.340 回答
0

我认为问题在于您在 class 中没有方法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();
    }
}
于 2013-03-27T23:26:15.603 回答