每当除以 0 或使用非整数时,我的计算器就会终止。我无法让我的 while 循环工作。
谁能帮忙,并解释我如何解决这个问题?
编辑:
它仍然终止。
package b;
import java.util.*;
public class Calculator3{
static boolean _state = true;
public static void main (String[] args){
System.out.println("Usage: operand1 operator operand2");
System.out.println("Operands are integers");
System.out.println("Operators: + - * /");
Scanner in = new Scanner(System.in);
do{
int result = 0;
int operand1 = 0;
int operand2 = 0;
String operator = " ";
char op = ' ';
try{
operand1 = in.nextInt();
operator = in.next();
op = operator.charAt(0);
operand2 = in.nextInt();}
catch (InputMismatchException e){
System.out.println("One or both of the operands are non-integers. Please check your operands");
break;}
try{
switch (op){
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: System.out.println("Unknown Operator");
break;}
}
catch(RuntimeException e){
System.out.println("Operand2 cannot be 0");
System.exit(0);}
finally{
System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result);}
}
while (_state = true);}}