I'm having some issues with a java calculator assignment I was handed. I was told to make a calculator that does very basic functions, catches exceptions and allows you to correct values for either operand or operator immediately (which is what I'm having problems with). For instance, this is what should happen in the console:
j * 6
Catch exception and print error message here and asking for new first operand
4
Answer: 4 * 6 = 24
or
8 h 9
Catch exception and print error message here asking for new operator
+
Answer: 8 + 9 = 17
This code is what I have so far:
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);
}
}