2012-05-16 48 views
1

我分配說扔一個嘗試,趕上這個:我似乎無法崩潰我的程序得到我想要的錯誤

  • 如果用戶不輸入至少3個令牌
  • 如果用戶不會輸入令牌1和3的有效數字。

我試圖研究它,我似乎無法找到這樣的例外。 現在我的例外似乎適用於上述兩個條件,但我的導師希望我有兩個捕獲,而不是一個。

我想能夠崩潰這個程序,所以我終於可以得到另一個拋出並捕獲或修改這個程序,以便異常會專門捕獲一件事情(就像只有當用戶沒有輸入至少3個令牌時)。

如果我嘗試做上述任何一種事情來使程序崩潰,順便說一下,它總是會給我我的錯誤信息,所以很明顯它似乎涵蓋了我上面提到的兩件事。

我的例外涵蓋了我需要捕捉的兩件事情,但我需要兩個捕獲物,而不是一個。

import java.util.NoSuchElementException; 
import java.util.Scanner; 
import java.util.StringTokenizer; 
public class Driver { 
    public static void main (String[] args) { 
     Scanner sc = new Scanner(System.in); 
     StringTokenizer st; 
     String input, tok1, tok2, tok3; 
     double dtok1, dtok3; 
     boolean loop = true; 

     //input 
     System.out.println("Simple calculator program"); 
     System.out.println("This program will only except a math expression with"); 
     System.out.println("2 operands and 1 operator. Exceptable operators"); 
     System.out.println("are +, -, *, /, and %. For example, 2*3 or 6%4."); 
     while (loop) { 
      System.out.print("\nplease enter an expression or q to quit: "); 
      try { 
       input = sc.next(); 

       if (input.equalsIgnoreCase("q")) { 
        loop = false; 
       } else { 
        //calculations 
        st = new StringTokenizer(input,"+-*/%",true); 
        tok1 = st.nextToken(); 
        tok2 = st.nextToken(); 
        tok3 = st.nextToken(); 
        dtok1 = Double.parseDouble(tok1); 
        dtok3 = Double.parseDouble(tok3); 
        System.out.println(input + "=" + 
        singleExpression(dtok1,dtok3,tok2)); 
       } 
      } catch (Exception NoSuchElementException) { 
       System.out.println ("Error! Please enter 2 operands and 1 operator!"); 
      } 
     } 
    } 

    static double singleExpression (double num1, double num2, String operator) { 
     double output = 0.0; 
     if (operator.equals("+")) { 
      output = num1 + num2; 
     } else if (operator.equals("-")) { 
      output = num1 - num2; 
     } else if (operator.equals("*")) { 
      output = num1 * num2; 
     } else if (operator.equals("/")) { 
      output = num1/num2; 
     } else if (operator.equals("%")) { 
      output = num1 % num2; 
     } else { 
      output = 0; 
     } 
     return output; 
    } 
} 
+1

趕上(例外NoSuchElementException異常)想想你想在這裏做什麼 – Sridhar

回答

1

我認爲你使用異常類作爲變量名,它應該是類變種。

異常會抓住任何東西(包括數量和幾個要素)

try{ 
.. 
} catch (NoSuchElementException nse) { 
    System.out.println ("Exception for the String Tokenizer"); 
}catch (NumberFormatException nfe) { 
    System.out.println ("Exception for the Number format"); 
} 
catch (Exception otherException) { 
    System.out.println ("Something else.. " + otherException.getMessage()); 
} 
相關問題