2012-08-01 84 views
0

我在寫一個簡單的程序來解釋線程。無法運行線程程序

爲什麼它顯示下面的錯誤。 任何人都可以幫助我。

public class Myth extends Thread { 
    public void run() { 
    int val=65; 
    try { 
     for(int i=0;i<26;i++) { 
     System.out.println((char)val); 
     val++; 
     sleep(500); 
     } 
    } 
    catch(InterruptedException e) { 
     System.out.println(e); 
    } 
    // error pops up on this bracket saying class interface or enum expected. 
    // error in this line says-- illegal start of expression 

    public static void main(String args[]) { 
     Myth obj=new Myth(); 
     obj.start(); 
    } 
    } 
} 
+4

而今年的問題格式獎授予...你! – 2012-08-01 07:41:29

+0

對不起,愚蠢的格式。匆忙。 :p – user1560596 2012-08-01 07:51:36

回答

1

你必須餘額雙開合curly括號。

public class Myth extends Thread{ 
public void run(){ 
    int val=65; 
    try{ 
     for(int i=0;i<26;i++){ 
     System.out.println((char)val); 
     val++; 
     sleep(500); 
     } 
    }catch(InterruptedException e){ 
     System.out.println(e); 
    } 
} 

public static void main(String args[]){ 
    Myth obj=new Myth(); 
    obj.start(); 
} 
} 
+0

非常感謝AVD真的幫助 – user1560596 2012-08-01 07:50:11

1

run()方法沒有正確關閉。在System.out.println(e);之後添加一個額外的結束榮譽,你應該很好去。

+0

非常感謝它,它真的幫助了很多mthmulders。 – user1560596 2012-08-01 07:50:02

+0

樂於幫助,歡迎來到Stack Overflow。如果此答案或任何其他人解決了您的問題,請將其標記爲已接受。 – mthmulders 2012-08-01 07:52:36

+0

非常感謝您的幫助mthmulders – user1560596 2012-08-01 07:55:36

0

以下是更正的代碼原因是您的run方法的正文未關閉。

public class Myth extends Thread { 

public void run() { 

    int val = 65; 
    try { 

     for (int i = 0; i < 26; i++) { 
      System.out.println((char) val); 

      val++; 

      sleep(500); 

     } 

    } 

    catch (InterruptedException e) { 
     System.out.println(e); 
    } 
} 

public static void main(String args[]) // error in this line says-- illegal 
             // start of expression 

{ 
    Myth obj = new Myth(); 
    obj.start(); 
} 
} 
+0

非常感謝amicngh.Your的幫助。 – user1560596 2012-08-01 07:59:29

0

main方法置於Myth.run()方法內。因爲它不應該是一個類的靜態函數。

public class Myth extends Thread { 
    public void run(){ 
     int val=65; 
     try { 
      for(int i=0;i<26;i++) 
      { 
       System.out.println((char)val); 
       val++; 
       sleep(500); 
      } 
     }catch(InterruptedException e){ 
      System.out.println(e); 
     } 
     // error pops up on this bracket saying class interface or enum expected. 
     // error in this line says-- illegal start of expression 

    } 
    public static void main(String args[]){ 
     Myth obj=new Myth(); 
     obj.start(); 
    } 
} 
+0

非常感謝Talha Ahmed Khan的幫助 – user1560596 2012-08-01 10:57:58

0

您的運行方法沒有通過大括號正確關閉。關閉並編譯它,那麼它應該沒問題。打開花括號時,關閉大括號是一種很好的做法。然後你開始在它們之間編寫代碼。這應該可以幫助你避免這種令人尷尬的愚蠢錯誤。

+0

非常感謝Sakthisundar的幫助 – user1560596 2012-08-01 10:57:37