While Loop 未正确循环 (Java)

While Loop not looping correctly (Java)

执行此程序时,计算完成后,不会要求用户再次输入整数。我需要它询问数字然后再次重复答案的过程,直到用户通过键入 0 退出。我必须使用循环,规范的一部分。

        while (true){
            //creating scanner scanner
            Scanner input = new Scanner(System.in);

            System.out.println("Welcome to my simple java calculator!");

            System.out.println("Enter first number: ");
            int x = input.nextInt();

            System.out.println("Enter second number: ");
            int y = input.nextInt();

            System.out.println("Press 0 to quit, 1 to add, 2 to subtract, 3 to Multiply, or 4 to divide");
            int operation = input.nextInt();

                while (true) {
                    if (operation == 1) {
                        System.out.println(x + y);
                    } else if (operation == 2) {
                        System.out.println(x - y);
                    } else if (operation == 3) {
                        System.out.println(x * y);
                    } else if (operation == 4) {
                        System.out.println(x / y);
                    } else if (operation == 0) {
                        break; //breaks from inner loop
                    } else {
                        System.out.println("Operation is invalid.");
                    }
                    x = input.nextInt();
                    y = input.nextInt();
                }
                if (operation == 0) {
                    break; //breaks from outer loop
                }
       }
    }
}

我希望程序无限执行直到用户退出,但经过一次计算后,它不再要求用户输入整数。

首先,您正在一次又一次地创建 Scanner 对象,这会降低程序的性能。第二件事你正在使用两个 while 循环。此外,您可以使用 returnswitch 关键字来简化您的代码。

您可以使用以下代码来解决您的问题。

Scanner input = new Scanner(System.in);
while (true) {
    System.out.println("Welcome to my simple java calculator!");

    System.out.println("Enter first number: ");
    int x = input.nextInt();

    System.out.println("Enter second number: ");
    int y = input.nextInt();

    System.out.println("Press 0 to quit, 1 to add, 2 to subtract, 3 to Multiply, or 4 to divide");
    int operation = input.nextInt();

    switch (operation){
        case 0:
              return;
        case 1:
              System.out.println(x + y);
              break;
        case 2:
              System.out.println(x - y);
              break;
        case 3:
              System.out.println(x * y);
              break;
        case 4:
              System.out.println(x / y);
              break;
        default:
              System.out.println("Operation is invalid");
              break;
    
    }
}