我正在为学校作业使用java编写一个简单的程序。我找不到创建infinte循环的方法。它是一个调查程序,我必须重新设计它所以它不仅只有5个人,但我想要的数量,直到我结束它。这是一个代码:
class morecoffee
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
int person, preference, nothing, sugar, sweetener, count, quit;
nothing = sugar = sweetener = 0;
for (count = 1; count <=5; count++)
{
System.out.println ("How do you sweeten your coffee?");
System.out.println ("1. I don't");
System.out.println ("2. With sugar?");
System.out.println ("3. With sweetener?");
System.out.println ("4. Quit");
preference = input.nextInt();
if (preference == 1)
nothing++;
else if (preference == 2)
sugar++;
else if (preference == 3)
sweetener++;
if (preference == 4)
count = 5;
}
count = count +1;
System.out.println ("Survey Report");
System.out.println ("=============");
System.out.println (nothing + " person don't sweeten coffee");
System.out.println (sugar + " person use sugar in coffee");
System.out.println (sweetener + " person use sweetener in coffee");
}
答案 0 :(得分:1)
for (;;)
{
System.out.println ("How do you sweeten your coffee?");
System.out.println ("1. I don't");
System.out.println ("2. With sugar?");
System.out.println ("3. With sweetener?");
System.out.println ("4. Quit");
preference = input.nextInt();
if (preference == 1)
nothing++;
else if (preference == 2)
sugar++;
else if (preference == 3)
sweetener++;
if (preference == 4)
break;
}
答案 1 :(得分:1)
更改
for (count = 1; count <=5; count++)
到
while (preference != 4)
{
// code
++count;
}
并删除
if (preference == 4)
count = 5;
答案 2 :(得分:1)
int count = 0;
while(true)
{
System.out.println ("How do you sweeten your coffee?");
System.out.println ("1. I don't");
System.out.println ("2. With sugar?");
System.out.println ("3. With sweetener?");
System.out.println ("4. Quit");
preference = input.nextInt();
if (preference == 1) {
nothing++;
} else if (preference == 2) {
sugar++;
} else if (preference == 3) {
sweetener++;
} else if (preference == 4) {
break;
}
count++;
}
System.out.println ("Survey Report");
System.out.println ("=============");
System.out.println (nothing + " person don't sweeten coffee");
System.out.println (sugar + " person use sugar in coffee");
System.out.println (sweetener + " person use sweetener in coffee");
如果答案是4,您必须将循环更改为无限并添加中断。
答案 3 :(得分:1)
要使其无限期运行
While(true){
}
如果您希望完成,请使用关键字'break'。这打破了循环。你可以在:
中使用它if(preference==4){
break;
}