我遇到了一些與我交給java計算器任務有關的問題。我被告知要製作一個非常基本功能的計算器,捕捉異常並允許您立即糾正操作數或操作符的值(這是我遇到的問題)。舉例來說,這是在控制檯應該發生什麼: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);
}
}
有什麼問題....? –
我提供了這個控制檯的示例,您可以立即重新輸入以前的無效值,我需要關於如何爲計算器編寫代碼的想法/示例。 –