0

I have this code, its supposed to ask the user for input and stop when the user inputs false. If its not, it is supposed to do different things based on what they enter.

//ask the user if they want to view the average
System.out.println("Do you want to view the average of your data? please answer with true or false?");
currentAnswer = scan.nextBoolean();
if(currentAnswer){
    System.out.println("If yes, please type in one of the following(type false to exit)\n calories - protein - weight - rating");

}
String option;
/***

This is where the problem is. The code prints "Please type in one of the following....." twice instead of once, otherwise it works as intended.

*/
while(currentAnswer){
    option = scan.nextLine();
    switch (option) {
        case "calories": System.out.println(dataAverage("calories"));
        break;
        case "protein": System.out.println(dataAverage("protein"));
            break;
        case "rating": System.out.println(dataAverage("rating"));
            break;
        case "weight": System.out.println(dataAverage("weight"));
            break;
        case "false": currentAnswer = false;
        break;

    }

        System.out.println(" Please type in one of the following(type false to exit)\n calories - protein - weight - rating");

}

I tried a do while loop, but the problem is still there. Any ideas?

Gh Fa
  • 1
  • I think the problem is, that your line `option = scan.nextLine()` at the first run of the loop reads the remaining part of the line where you enter `true`. if you press enter immediatly after `true` this is only a linebreak. Adding `scan.nextLine` after the codeline where you read your boolean should fix this. – csalmhof Dec 29 '22 at 07:49
  • In cases like this I might try adding a debug line on the `option` variable to see if any of the switch statements are getting hit or not. If not that might indicate the input is not quite what you expect – fbailey Dec 29 '22 at 07:51

0 Answers0