0

My while loop for some reason keeps skipping over my input line. My code is as follows:

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

Once it gets to the end of the loop where it asks you if you want to eat again,the while loop just terminates right there and goes to the end of the program instead of giving me the option to input. I can't figure out why it's doing that. Thanks in advance.

0

2 Answers 2

3

This is because of how Scanner.nextInt() and Scanner.nextLine() work. If the Scanner reads an int and then ends up at the end of the line, Scanner.nextLine() will instantly just notice the line break and give you the remaining line (which is empty).

After the nextInt() call, add a input.nextLine() call:

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

That should fix it.

Sign up to request clarification or add additional context in comments.

Comments

0

My while loop for some reason keeps skipping over my input line.

Use next() instead of nextLine(). Change your while loop like below:

  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();
     //....
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.