2012-05-16 113 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()); 
} 
相关问题