2013-10-23 91 views
0

我是一名Java初學者,並試圖捕獲異常'InputMismatchException'。以下是我的代碼,我希望它很容易閱讀,如果格式不正確,請提前致歉。它建立良好並且執行,但是如果我輸入一個字符,例如'catch'不起作用並且出現錯誤;(Java)無法捕捉異常

「異常線程‘main’java.util.InputMismatchException」

我相信一切的代碼工作正常包括「嘗試」了,我沒有什麼比一個其他漁獲會System.out.print命令。

import java.util.*; // imports 

public class w4q1 

    { 
     public static void main(String[] args) 
     { 
      Scanner user_input = new Scanner(System.in); // declaring Scanner util 
       System.out.print("Please enter an integer: \n"); // Asks for input 
       int d = user_input.nextInt(); 

     while (d > 0 || d < 0) // start of while loop, in the event of anything other than zero entered 
     { 
      try { 

        if (d < 0) // if statements 
        { 
        System.out.print("The integer " + d + " is negative\n"); 
        break; 
        } 

          else if (d > 0) 
          { 
          System.out.print("The integer " + d + " is positive\n"); 
          break; 
          } 

           else 
           { 
           System.out.print("You have not entered an integer\n"); 
           break; 
           } 

       } 

       catch (InputMismatchException e) // Error message for letters/characters and decimals 
        { 
         System.out.print("You have entered an incorrect value, please restart the program\n"); 
        } 



     } 

     if (d == 0) 
      { 
      System.out.print("A zero has been entered\n"); 
      } 

     } 
    } 
+2

'int d = user_input.nextInt();'應該在'try'塊內。 –

回答

1

如果仍然收到即使你有一個try-catch塊的InputMismatchException,則例外,必須從某處降臨到你的try-catch塊之外。

看看try-catch塊外面還有什麼可以拋出InputMismatchException並在該語句周圍放置一個try-catch塊,或者擴展現有的try-catch塊以包含該語句。

+0

嗯,你是對的我想,我有user_input.nextInt之外的try塊導致它不能捕獲。謝謝 ! :) – I2obiN

0

如果確實沒有發現異常,則生成的堆棧跟蹤應該顯示引發異常的實際代碼行。看代碼,我會猜測這是在異常發生:

user_input.nextInt(); 

我建議你看看堆棧跟蹤,看看你是否可以證實這一點。

0

將一個try-catch塊解決此代碼

INT d = user_input.nextInt();

通過這樣做,您還需要將當前代碼稍微更改一點,以使其可以正常工作。祝你好運 !