【问题标题】:Java program doesn't have any output when using a switch statement inside a while loop?在while循环中使用switch语句时Java程序没有任何输出?
【发布时间】:2016-04-07 22:30:58
【问题描述】:

所以我需要 while 循环中的语句重复,直到用户输入 4(退出程序),但是当我尝试运行程序时,没有任何内容输出到屏幕上(但它编译得很好)。为什么会这样做?这个答案可能很简单,但任何帮助都将不胜感激!

public class Driver 
{
public static void main(String[] args) 
{
    Scanner keyboard = new Scanner(System.in);
    int answer;
    boolean bool = true;

    while(bool);
    {
        System.out.println("\n\tGeometry Calculator\n" + 
                            "\t1. Calculate the Area of a Circle\n" +
                            "\t2. Calculate the Area of a Rectangle\n" +
                            "\t3. Calculate the Area of a Triangle\n" +
                            "\t4. Quit\n");
        System.out.print("\tEnter your choice (1-4): ");
        answer = keyboard.nextInt();

        switch(answer)
        {
            case 1:
                System.out.println("\n\tCalculating the area of a circle...");
                break;
            case 2:
                System.out.println("\n\tCalculating the area of a rectangle...");
                break;
            case 3:
                System.out.println("\n\tCalculating the area of a triangle...");
                break;
            case 4:
                System.out.println("\n\tQuiting...");
                System.exit(0);
                break;
            default:
                System.out.println("\n\tPlease enter a number between 1 and 4.");
        }

        if(answer == 4)
            bool = false;
    }
}

【问题讨论】:

  • 删除while循环条件后面的分号。
  • @rgettman 哇,它工作得很好,真是个愚蠢的错误。谢谢!
  • 你的bool变量当前是多余的:你不仅可以用while (true)和if (answer == 4) break替换它,你还可以删除if (answer == 4),因为你System.exit在case 4 .或者,您可以删除if (answer == 4) 条件并将System.exit(0) 替换为bool = false。

标签: java while-loop switch-statement


【解决方案1】:

你犯了一个小错误。您在 while 循环之后添加了 ;。只需删除它。你的代码应该是

while(bool)

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2018-09-16
    • 2021-07-22
    • 2014-05-14
    • 1970-01-01
    相关资源
    最近更新 更多