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

4
在我的Java程序中,我使用了一个布尔变量“decision”,只有在变量为true时才应该执行“do循环代码块”中的实际计算器代码,但是即使决策变量为false,do while循环仍然会被执行。我正在使用Java的Eclipse集成开发环境和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);
  }
}

1
你可以使用 if/else 语句来决定是否需要循环,或者仅仅改用 while 循环。 - GhostCat
1
这就是 do..while 循环的作用。循环体至少会被执行一次。使用 while 循环。 - Thiyagu
感谢大家的建议和修复,帮了我很多。问题已经解决! - Yogi Raj
2个回答

2

即使决策变量为false,do while循环也会执行。

do...while会在检查条件之前先执行一次循环体。

要么修改您的代码使用while,要么添加一个包含do...whileif-else语句块。


谢谢大家的建议和修复,都帮了我很多。问题已经解决了! - Yogi Raj

1
你可以添加另一个case 5,并在其中编写System.exit(0)以成功终止程序。
while部分传递(option != 5)。这应该运行程序。 你不需要决策变量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接