我在交给我的 Java 计算器作业时遇到了一些问题。我被告知要制作一个计算器,它可以执行非常基本的功能,捕获异常并允许您立即更正操作数或运算符的值(这是我遇到的问题)。例如,这应该在控制台中发生:
j * 6
Catch exception and print error message here and asking for new first operand
4
Answer: 4 * 6 = 24
或者
8 h 9
Catch exception and print error message here asking for new operator
+
Answer: 8 + 9 = 17
这段代码是我到目前为止所拥有的:
import java.util.*;
public class Calculator{
static int _state = 3;
public static void main(String[] args){
_state = 3;
System.out.println("Usage: operand1 operator operand2");
System.out.println(" (operands are integers)");
System.out.println(" (operators: + - * /");
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
do{
try{
int result = 0;
int operand1 = 0;
int operand2 = 0;
String operator = "";
char op = ' ';
operand1 = in.nextInt();
operator = in.next();
op = operator.charAt(0);
operand2 = in.nextInt();
switch (op){
default:
System.out.println("You didn't insert a proper operator");
break;
case '+': result = operand1 + operand2;
System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
break;
case '-': result = operand1 - operand2;
System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
break;
case '*': result = operand1 * operand2;
System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
break;
case '/': result = operand1 / operand2;
System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
break;
}
}
catch(ArithmeticException e){
System.out.println("You can not divide by zero. Input a valid divider.");
}
catch (InputMismatchException e) {
System.out.println("You must use proper numerals.");
}
} while(_state == 3);
}
}