Lucas Clarke
Lucas Clarke

Reputation: 21

Java Identifier Not Working

So I have a car class and a car tester class. Here is the car class:

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;
    }
}

And here is the problem. In my carTester class, why doesnt myVehicle.drive(); work?? It underlines it in red (netBeans) and says "package myVehicle doesn't exist"

package main;

public class CarTester {

    Car myVehicle = new Car();
    myVehicle.drive();
    double gasLeft = myVehicle.getGasInTank();
}

Upvotes: 0

Views: 197

Answers (3)

Reimeus
Reimeus

Reputation: 159874

The compiler will issue this message when you attempt to invoke an operation on an Object in the class block.

You need to use a main method in CarTester. Also you need to supply a double distance value as per your drive method.

public class CarTester {
  public final static void main(String[] args) {
    Car myVehicle = new Car();
    myVehicle.drive(33.2);
    ...
  }
}

Upvotes: 2

feralin
feralin

Reputation: 3418

I think what the problem is is that you don't have a method in class CarTester. The compiler is complaining that it cannot find a package with the name of myVehicle, because it is trying to interpret the line myVehicle.drive(); as a type. You need to change the class CarTester to something like:

public class CarTester
{
    public static void main(string[] args)
    {
        Car car = new Car();
        car.drive(10.0);
        double gasLeft = car.getGasInTank();
    }
}

Upvotes: 0

user1697575
user1697575

Reputation: 2848

run your code in CarTester class inside of the method. for example 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();
  }
}

Upvotes: 0

Related Questions