2013-03-04 229 views
0

我想以後我成功編譯它的載重車輛類,但這個錯誤occures: Error: could not find or load main class VehicleJava錯誤:找不到或無法加載主類車輛

我認爲有可能是在我的代碼錯誤,其中是以下內容:

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

    } 
} 
+2

錯誤不在您的代碼中,而是在您用來啓動它的命令中。 – 2013-03-04 11:34:44

+0

你是什麼意思? – 2013-03-04 14:10:49

+0

我的意思是你發佈了所有不相關的信息,而且沒有任何相關的信息。就目前而言,你無法幫助解決這個問題。 – 2013-03-04 14:27:29

回答

1

問題不在於您的代碼中,而在於您如何啓動它。

找到您的類文件編譯到的位置,並將此根添加到您的類路徑中。

例如,如果你的類文件被編譯爲:

<project root>/classes 

然後你就可以運行如下這些:

java -cp <project root>/classes Vehicle 

就這個題目一看Oracle Documentation更多細節

+0

我正在使用我命令提示符來測試它。有什麼地方可以運行嗎?我也會檢查你所說的位置 – 2013-03-04 12:50:59

+0

我試過你的解決方案,但同樣的錯誤發生。如果javac Vehicle.java已經運行了一個名爲Vehicle.class的文件應該已經創建好了嗎?似乎沒有創建這樣的文件 – 2013-03-04 13:26:25

+0

如果javac Vehicle.java報告成功,那麼將生成一個類文件 - 我們只需要找出在哪裏:-)您是通過IDE還是通過命令創建它提示?如果從提示符中可以試試這個:javac -d。 Vehicle.java - 這應該在你所在的同一目錄中生成類文件 - 你可以試試這個,讓我知道它是否有效? – 2013-03-04 13:31:43

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! 

代碼工程

+0

Vehicle.class不會創建時,我執行以下操作:javac Vehicle.java – 2013-03-04 13:37:40

相關問題