0

我在成功编译后尝试加载 Vehicle 类,但出现此错误: Error: could not find or load main class Vehicle

我认为我的代码中可能存在错误,如下所示:

public class Vehicle
{
    String make;
    String color;
    boolean engineState;

    void startEngine()
    {
       if (engineState == true)
          System.out.println("The engine is already on!");
       else
       {
           engineState = true;
           System.out.println("The engine is now on.");
       }
    }

    void showAttributes()
    {
      System.out.println("This vehicle is a " + color + "
      " + make);
      if (engineState == true)
        System.out.println("The engine is on.");
      else
        System.out.println("The engine is off.");
    }

    public static void main(String args[])
    {
        // Create a new vehicle and set its attributes.
        Vehicle car = new Vehicle();
        car.make = "Rolls Royce";
        car.color = "Midnight blue";
        System.out.println("Calling showAttributes ...");
        car.showAttributes();

        System.out.println("--------");
        System.out.println("Starting the engine ...");
        car.startEngine();
        System.out.println("--------");
        System.out.println("Calling showAttributes ...");
        car.showAttributes();

        // Let’s try to start the engine again.
        System.out.println("--------");
        System.out.println("Starting the engine ...");
        car.startEngine();

    }
}
4

2 回答 2

1

问题不在于您的代码,而在于您如何启动它。

找到你的类文件被编译到的位置,并将这个根添加到你的类路径中。

例如,如果您的类文件被编译为:

<project root>/classes

然后您可以按如下方式运行它们:

java -cp <project root>/classes Vehicle

查看有关该主题的Oracle 文档以获取更多详细信息

于 2013-03-04T11:39:26.703 回答
0

在我的日食中工作正常,结果如下:

Calling showAttributes ...
This vehicle is a Midnight blueRolls Royce
The engine is off.
--------
Starting the engine ...
The engine is now on.
--------
Calling showAttributes ...
This vehicle is a Midnight blueRolls Royce
The engine is on.
--------
Starting the engine ...
The engine is already on!

代码有效

于 2013-03-04T11:39:43.177 回答