2013-10-11 57 views
0

我終於(幾乎)完成了一個我一直在努力的計算器項目。目前,它可以與加法,減法,乘法,除法,mod,平方和否定雙打,並響應某些字符串,如「退出」,「清除」和「幫助」。實現一個try和catch塊

我只需要幫助實現一個try和catch塊來在控制檯返回一個消息,比如「輸入無效」,只要用戶輸入任何不是數字的東西后控制檯說「輸入第一個數字」或「輸入第二個數」。

我已經搞砸了幾種不同的方法,但似乎沒有任何工作。建議將不勝感激。 代碼:

import java.util.Scanner; 


public class exit { 

    static double num1; 
    static double num2; 
    static String operation; 

    public static void main(String[] args) { 

     boolean run = true; 

     while (run) { 

      System.out.println(" Enter: \n \b help for all usable operations \n continue to use the calculator"); 
      Scanner input = new Scanner(System.in); 
      String str1 = input.next(); 

      if (str1.equals("exit")) { 

       System.exit(0); 
      } else if (str1.equals("clear")) { 

       System.out.println("0.0"); 
      } else if (str1.equals("help")) { 
       System.out.println("please enter:\n + for addition \n - for subtraction \n * for  multiplication \n/for division \n -x for negation \n x^2 for squaring\n % for mod \n remember to only input integer or double values\n"); 

      } else if (str1.equals("continue")) { 

       System.out.println("\nEnter the first number:"); 
       num1 = input.nextInt(); 


       System.out.println 
         ("Display:" + num1); 

       System.out.println("Please enter operation:"); 
       operation = input.next(); 


       System.out.println("Enter the second number:"); 
       num2 = input.nextInt(); 
       System.out.println("Display:" + num2); 


       if ("+".equals(operation)) { 

        System.out.println((num1 + num2)); 
       } else if ("-".equals(operation)) { 

        System.out.println((num1 - num2)); 
       } else if ("/".equals(operation)) { 

        System.out.println((num1/num2)); 
       } else if ("*".equals(operation)) { 

        System.out.println((num1 * num2)); 
       } else if ("-x".equals(operation)) { 

        System.out.println(-num1); 
       } else if ("x^2".equals(operation)) { 

        System.out.println(num1 * num1); 
       } else if ("sqrt".equals(operation)) { 

        System.out.println(Math.sqrt(num1)); 

       } 


      } 

     } 
    } 
} 
+1

爲什麼你需要試試看?你可以檢查數字只在'如果'或設置輸入字符只有整數 – user2377971

+1

http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner –

回答

3

要檢查數量的通過實現try-catch的有效性,你可以嘗試做這樣的事情:

try{ 
    Double num = Double.parseDouble(input.nextLine()); // This is just a sample 
    // int someInt = Integer.parseInt(someBasString); // Even this will throw NFE 
}catch(NumberFormatException NFE){ // If its not a valid number, you'll get this exception 
    // Do something on error 
} 
0

您可以使用此

try{ 
num1 = input.nextInt(); 
.. 
num2 = input.nextInt(); 
} 
catch(Exception ex) 
{ 
    System.out.println("Invalid input") 
} 

到在捕獲'Exception'之前做得更好,你可以捕獲'InputMismatchException'或任何你期待的其他異常。這樣你可以顯示更多的相關信息趕上。