在 Java 计算器程序中执行 do while 循环

Execution of do while loop in the Java Calculator program

在我的 Java 程序中,我使用了一个布尔变量 'decision',只有当该变量为真时,它才应该在 'do loop code block' 中执行实际的计算器代码,但是即使决策变量为假,循环仍会执行。我将 Eclipse IDE 用于 Java 和 JDK 10(均为最新版本)。请帮我解决。代码如下

import java.util.Scanner;

public class apples {

public static void main(String[] args) {

    int option,a,b,c;
    boolean decision;
    System.out.println("We are here to create a calculator");
    System.out.print("Do you want to switch on the calculator:");
    Scanner yogi = new Scanner(System.in);
    decision = yogi.nextBoolean();
    do {
        System.out.println("Following operations are available to perform:");
        System.out.println("1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Multiplication");
        System.out.println("4. Division");
        System.out.print("Enter the operations do you want to perform:");
        option = yogi.nextInt();
        System.out.println("Choice of operation is:"+option);

        switch(option) {

        case 1:
            System.out.println("Enter two numbers to be added:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a + b;
            System.out.print("Addition:"+c);
            break;

        case 2:
            System.out.println("Enter two numbers to be subtracted:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a - b;
            System.out.print("subtracted:"+c);
            break;

        case 3:
            System.out.println("Enter two numbers to be multiplied:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a * b;
            System.out.print("multiplied:"+c);
            break;

        case 4:
            System.out.println("Enter two numbers to be divided:");
            a = yogi.nextInt();
            b = yogi.nextInt();
            c = a / b;
            System.out.print("divided:"+c);
            break;

        default:
            System.out.println("This is a wrong choice");
            break;
        }
    }while(decision==true);
  }
}

the do while loop is executed anyways even when the decision variable is false

A do...while 将在检查条件之前执行一次正文。

要么修改 while 的代码,要么添加 if-else 包围 do...while

您可以添加另一个 case 5 并在其中写入 System.exit(0) 以成功终止程序。

while部分传递(option != 5)。这应该是运行的程序。 您不需要决策变量。