0

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));
    }
}
  • 1
    There are few errors in logic. For instance `divideByZero.equals(divideByZero)` will always be true (unless there are other threads involved, but it is not the case here). Same about `notValidInput.equals(notValidInput)` and `exception.equals(exception)`. – Pshemo May 26 '22 at 17:34
  • 2
    Also you are calling `scan.close();` in first iteration of your loop which means in next iteration you can't use `scan` or `System.in`. – Pshemo May 26 '22 at 17:36

0 Answers0