【发布时间】: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