渡された 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);
}
}