I'm trying to write a simple calculator, I want to restart the program when an error occurs. The problem is that "while" works incorrectly. When I enter incorrect data, "while" starts to work infinite.
Can you give me a hint or advice?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String divideByZero = "Cannot divide by zero";
String notValidInput = "Not a valid input data";
String exception = "Wrong input data";
do {
try {
System.out.println("Write a number one");
int operand1 = scan.nextInt();
System.out.println("Write a sign of arithmetic operation");
String sign = scan.next();
System.out.println("Write a number two");
int operand2 = scan.nextInt();
switch (sign) {
case "+":
System.out.println(operand1 + operand2);
break;
case "-":
System.out.println(operand1 - operand2);
break;
case "*":
System.out.println(operand1 * operand2);
break;
case "/":
if (operand2 == 0)
System.out.println(divideByZero);
else
System.out.println(operand1 / operand2);
break;
default:
System.out.println(notValidInput);
break;
}
} catch (Exception e) {
System.out.print(exception);
} finally {
scan.close();
}
} while (divideByZero.equals(divideByZero) || notValidInput.equals(notValidInput)
|| exception.equals(exception));
}
}