2014-04-28 18 views
0

如圖所示,我已經放入了try catch,程序仍然跳到第二個輸入問題(「輸入您的操作:加,減,除,乘或退出」之後),而不打印錯誤異常。另外,如果輸入第一個問題的「退出」,第二個輸入需求在程序完成之前仍然會循環,那麼有什麼方法可以根據其他輸入的提示立即退出嗎? 任何建議,歡迎嘗試在程序設計中發現放置問題?

import java.util.Scanner; 
import java.io.*; 


class Monday { 
    public static void main(String[] args) { 
    double n1,n2; 
    boolean check = true; 

    while(check) { 
     System.out.println("Enter your operation: add, subtract, divide, multiply, or exit"); 
     Scanner myScan = new Scanner(System.in); 
     String op = myScan.next(); 
     try { 
      System.out.println("Enter your 1st number"); 
      try { 
       n1 = myScan.nextDouble(); 
       System.out.println("Enter your 2nd number"); 
       n2 = myScan.nextDouble(); 
      } catch (Exception e) { 
       System.out.println("This is my error"); 
       return; 
      } 

     /* System.out.println("Enter your 1st number"); 
      n1 = myScan.nextDouble(); 
      System.out.println("Enter your 2nd number"); 
      n2 = myScan.nextDouble();*/ 




      switch (op) { 
       case"add": 
       System.out.println("Your answer is "+ (n1 + n2)); 
       break; 

       case"subtract": 
       System.out.println("Your answer is "+ (n1 - n2)); 
       break; 

       case"divide": 
       System.out.println("Your answer is "+ (n1/n2)); 
       break; 

       case"multiply": 
       System.out.println("Your answer is "+ (n1 * n2)) ; 
       break; 

       case"exit": 
       System.out.println("Goodbye!"); 
       break; 

      } 


      if ("exit".equals(op)) 
      check = false; 

     } catch (Exception e) { 
      System.out.println("This is my error"); 

      System.exit(1); 
     } 
    } 
} 

}

回答

0

你甚至都不需要try/catch語句。

double n1, n2; 
System.out.println("Enter your 1st number"); 
if (myScan.hasNextDouble()) n1 = myScan.nextDouble(); 
else return; 
System.out.println("Enter your 2nd number"); 
if (myScan.hasNextDouble()) n2 = myScan.nextDouble(); 
else return; 

但是,如果你想使用它:

double n1, n2; 
System.out.println("Enter your 1st number"); 
try { 
    n1 = myScan.nextDouble(); 
    System.out.println("Enter your 2nd number"); 
    n2 = myScan.nextDouble(); 
} catch (Exception e) { 
    System.out.println("This is my error"); 
    return; 
} 
+0

對不起沒有解釋自己非常好,我希望程序,如果我的第一個問題後,不輸入正確的操作給出一個錯誤「 System.out.println(「輸入您的操作:加,減,除,乘或退出」);「並且如果輸入退出以使程序結束而不詢問進一步的問題。 –

+0

見編輯回答。 –

+0

謝謝你,但這不會影響下面的switch語句和循環?將不會被編譯爲「字符串操作」不再被識別。 –