【问题标题】:While loop won't loop虽然循环不会循环
【发布时间】: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


    【解决方案1】:

    这是因为 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
    

    这应该可以解决它。

    【讨论】:

      【解决方案2】:

      由于某种原因,我的 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();
           //....
        }
      

      【讨论】:

        猜你喜欢
        • 2015-09-14
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2016-06-14
        • 2013-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多