簡體   English   中英

While循環不會循環

[英]While loop won't 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循環就在那里終止並轉到程序的結尾,而不是讓我選擇輸入。 我不知道為什么要這么做。 提前致謝。

這是因為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

那應該解決它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM