2015-10-20 55 views
1

在執行下面的類時,將拋出「線程'main'java.lang.NoClassDefFoundError」中的異常。我預計這個例外將被拋出爲「MainMethodNotFoundException」。線程「main」中的異常java.lang.NoClassDefFoundError而不是MainMethodNotFound

爲什麼noClassDefFoundError在這裏被拋出?

public class TestingSwitch { 
    public static void main(String args) { 
     int cnt = 1; 
     switch(cnt){ 
      default: 
       System.out.println("Welcome"); 
      case 1: 
       System.out.println("One"); 
       break; 
      case 2: 
       System.out.println("Two"); 
       break; 
     } 
    } 

}

+0

你是怎麼執行的這個代碼?你能告訴我們你用來執行java的命令嗎? – jfcorugedo

+0

夥計 我很確定主要方法簽名是錯誤的。 但我期待的答案是:爲什麼「NoClassDefFoundError」而不是MainMethodNotFound? –

+0

是的,我明白了。但它取決於你用來執行類的命令。你確定你在控制檯中鍵入的類是否存在並被編譯? – jfcorugedo

回答

1

錯方法簽名。

變化:

public static void main(String args) 

要:

+0

總是包含java.lang' – jfcorugedo

1

你必須改變public static void main(String args)public static void main(String[] args)

來看,這種

public class Test { 

     public static void main(String[] args) { 
      int cnt = 1; 
      switch(cnt){ 
       default: 
        System.out.println("Welcome"); 
       case 1: 
        System.out.println("One"); 
        break; 
       case 2: 
        System.out.println("Two"); 
        break; 
      } 
     } 

} 
1

這裏是你的錯誤:

public static void main(String args) 

你必須寫

0

我試過你的代碼,它給了我一個不同的錯誤。

這是我試過的步驟:

  1. 創建一個類TestingSwitch

    vi TestingSwitch.java 
    
  2. 放在那裏,你的內容

    $ cat TestingSwitch.java 
    public class TestingSwitch { 
        public static void main(String args) { 
         int cnt = 1; 
         switch(cnt){ 
         default: 
          System.out.println("Welcome"); 
         case 1: 
          System.out.println("One"); 
          break; 
         case 2: 
          System.out.println("Two"); 
          break; 
         } 
        } 
    } 
    
  3. 編譯類

    javac TestingSwitch.java 
    
  4. 現在有目錄中的兩個文件

    -rw-r--r-- 1 xxxx xxxx 518 Oct 26 11:33 TestingSwitch.class 
    -rw-r--r-- 1 xxxx xxxx 373 Oct 26 11:33 TestingSwitch.java 
    
  5. 嘗試執行類:

    $ java TestingSwitch 
    Error: Main method not found in class TestingSwitch, please define the main method as: 
    public static void main(String[] args) 
    or a JavaFX application class must extend javafx.application.Application 
    

我使用Oracle JDK 1.8:

java version "1.8.0_31" 
    Java(TM) SE Runtime Environment (build 1.8.0_31-b13) 
+0

是的,我也在Java 8中嘗試過.......它拋出Main方法沒找到,就像你的一樣 –

相關問題