2016-07-24 104 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 
} ...