1
我的代码似乎进入了一个无限循环,我对为什么感到困惑。我介绍的代码段,直到我触发错误消息:为什么我的java代码进入无限循环?
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int count = 0;
double sum = 0;
System.out.print("Enter a value: ");
boolean notDone = true;
while (notDone)//go into loop automatically
{
if(!in.hasNextDouble()){
if(count==0){//this part generates bugs
System.out.print("Error: No input");
}else{
notDone = false;
}
}else{
sum+= in.nextDouble();
count++;
System.out.print("Enter a value, Q to quit: ");
}
}
double average = sum/count;
System.out.printf("Average: %.2f\n", average);
return;
}
}
正如评论指出,罪魁祸首就是这几行:
if(count==0){ //this part generates bugs
System.out.print("Error: No input");
}
这样做的目的,如果情况是这样用户停留在循环中,并提醒需要有效的输入,直到它接收到有效的输入为止,但它不像是没有办法摆脱循环,因为用户可以在程序接收的情况下摆脱循环有效的输入(至少一个双精度值,后跟一个非双精度值)。
干杯。