2013-11-21 81 views
0

我的while循環由於某種原因不斷跳過我的輸入行。我的代碼如下:雖然循環將不會循環

import java.util.Scanner; 
public class CalorieCalculator { 

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    Calories[] array = {new Calories("spinach", 23), new Calories("potato", 160), new Calories("yogurt", 230), new Calories("milk", 85), 
      new Calories("bread", 65), new Calories("rice", 178), new Calories("watermelon", 110), new Calories("papaya", 156), 
      new Calories("tuna", 575), new Calories("lobster", 405)}; 
    System.out.print("Do you want to eat food <Y or N>? "); 
    String answer = input.nextLine(); 
    int totalCal = 0; 
    while (answer.equalsIgnoreCase("y")){ 
     System.out.print("What kind of food would you like?"); 
     String answer2 = input.nextLine(); 
     System.out.print("How many servings?: "); 
     int servings = input.nextInt(); 
     for (int i = 0; i < array.length; i++){ 
      if (array[i].getName().equalsIgnoreCase(answer2)) 
       totalCal = totalCal + (servings*array[i].getCalorie()); 
     }//end for loop 
     System.out.print("Do you want to eat more food <Y or N>? "); 
     answer = input.nextLine(); 
    }//end while loop 
    System.out.println("The total calories of your meal are " + totalCal); 

}//end main method 
}//end CalorieCalculator class 

一旦它到達的地方,如果你想再吃問你的循環結束,while循環剛剛結束在那裏,進到程序的結束,而不是給我選擇輸入。我無法弄清楚爲什麼這樣做。提前致謝。

回答

3

這是因爲Scanner.nextInt()Scanner.nextLine()是如何工作的。如果Scanner讀取的是int,然後在行尾結束,Scanner.nextLine()將立即注意到換行符,併爲您提供剩餘的行(空的行)。

nextInt()電話後,添加input.nextLine()電話:

int servings = input.nextInt(); 
input.nextLine(); //this is the empty remainder of the line 

這應該修復它。

0

我的while循環由於某種原因不斷跳過我的輸入行。

使用next()而不是nextLine()。更改您的while循環,如下所示:

int totalCal = 0; 
    while (true){ 
     System.out.print("Do you want to eat food <Y or N>? "); 
    String answer = input.nextLine(); 

    if("N".equalsIgnoreCase(answer)){ 
     break; 
    } 

    System.out.print("What kind of food would you like?"); 
    String answer2 = input.next(); 
    System.out.print("How many servings?: "); 
    int servings = input.nextInt(); 
    //.... 
    }