【发布时间】:2013-11-21 16:59:48
【问题描述】:
由于某种原因,我的 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 循环就在那里终止并进入程序的末尾,而不是让我选择输入。我不明白为什么会这样。提前致谢。
【问题讨论】:
标签: java while-loop