2016-07-24 72 views
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"); 
       } 

这样做的目的,如果情况是这样用户停留在循环中,并提醒需要有效的输入,直到它接收到有效的输入为止,但它不像是没有办法摆脱循环,因为用户可以在程序接收的情况下摆脱循环有效的输入(至少一个双精度值,后跟一个非双精度值)。

干杯。

回答

2

您的代码进入无限循环,因为如果未检测到double,则条件不会取得任何进展。发生这种情况时,您会打印一条消息,但不会从扫描仪中删除垃圾输入。

添加in.nextLine()到有条件的将解决这个问题:

if(!in.hasNextDouble()){ 
    if (!in.hasNextLine()) { 
     // The input is closed - exit the program. 
     System.out.print("Input is closed. Exiting."); 
     return; 
    } 
    in.nextLine(); 
    ... // The rest of your code 
} ...