2012-03-20 26 views
1

程序會要求輸入一個整數。我在catch方法中設置了一個錯誤消息,以防輸入是字符或除了整數之外的任何東西。但是,當我嘗試輸入字母時,我看不到錯誤消息。我也嘗試過不同的Exception類型和相應的導入,但沒有區別。下面的代碼:沒有看到我在catch方法中設置的錯誤消息(Java)

public class Random1 { 

public static void main(String[] args){ 

    int g; 

    Scanner input = new Scanner(System.in); 

    System.out.print("Enter your guess: "); 
    g = input.nextInt(); 


    Random r = new Random(); 
    int a = r.nextInt(10) + 1; 

    try { 
     if (g == a) { 

      System.out.println("**************"); 
      System.out.println("* YOU WON! *"); 
      System.out.println("**************"); 
      System.out.println("Thank you for playing!"); 

     } else if (g != a) { 
      System.out.println("Sorry, better luck next time!"); 
     } 
    } catch (Exception e) { 
     System.err.println("Not a valid input. Error :" + e.getMessage()); 

    } 
+0

嘗試添加去的代碼 「的System.out.println(G);」在g = input.nextInt()之後。當你輸入一個字母時,看看你在這裏得到了什麼 – mfrankli 2012-03-20 00:55:28

+0

錯誤,但不是我在catch方法上寫的那個。 – singko 2012-03-20 00:58:11

+0

Theres在您的try/catch塊中可能會出現錯誤,如果您想檢查輸入的有效性,請將'g = input.nextInt();'行移入try/catch塊。或者像mfrankli所說的那樣,只要把'System.out.println(g);'放在最後或者測試輸出。 – John 2012-03-20 01:00:07

回答

6

拋出異常必須在try塊

+0

明白了。謝謝 :) – singko 2012-03-20 01:04:04

相關問題