Java 我能';Don’我似乎不会为了得到我想要的错误而使我的程序崩溃
我的作业是要试着抓住它:Java 我能';Don’我似乎不会为了得到我想要的错误而使我的程序崩溃,java,Java,我的作业是要试着抓住它: 如果用户未输入至少3个令牌 如果用户没有为令牌1和令牌3输入有效数字 我试着研究它,但我似乎找不到一个例外。 现在我的例外似乎适用于上述两个条件,但我的导师希望我有两个捕获,而不是一个 我希望能够使该程序崩溃,以便最终获得另一个抛出并捕获或修改该程序,以便异常能够捕获一件特定的事情(例如,仅当用户未输入至少3个令牌时) 如果我试着做上面的任何一件事来破坏这个程序,顺便说一句,它总是会给我错误信息,所以它显然涵盖了我上面的两件事 我的例外包括我需要抓住的两件事,但我需
- 如果用户未输入至少3个令牌
- 如果用户没有为令牌1和令牌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;
}
}
如果此标记器的字符串中没有更多标记。你已经看到了
如果字符串不包含可解析双精度
2评论:
- (虽然没有弃用)-您可以使用
String#split
- 您的catch子句应该如下所示:
catch(NoSuchElementException e)
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() );
}