虽然循环不会循环

时间:2013-11-21 16:59:48

标签: java while-loop

我的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循环就在那里终止并进入程序的结尾,而不是给我输入的选项。我无法弄清楚为什么会这样做。提前谢谢。

2 个答案:

答案 0 :(得分:3)

这是因为Scanner.nextInt()Scanner.nextLine()的工作方式。如果Scanner读取int,然后在该行的末尾结束,Scanner.nextLine()会立即注意到换行符,并为您提供剩余行(为空)。< / p>

nextInt()来电之后,添加input.nextLine()来电:

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

那应该解决它。

答案 1 :(得分: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();
     //....
  }