0

Please help me understand why the while loop prompts the statement "enter am or pm" twice. I need it to ask only once and wait for an input. Only if the input in invalid, should the loop execute again.

System.out.println(" ");

int startHour=0;

boolean validAnswerOne=false;

while (validAnswerOne == false){ 

  System.out.println("Enter the starting hour: ");

  startHour = input.nextInt();

  if (startHour<=12){

    validAnswerOne=true;

  }
}


String validAnswerTwo = "False";

while (validAnswerTwo.equals("False"))
{

  System.out.println("Enter am or pm: ");

  String time = input.nextLine();

  time = time.toLowerCase();


  if (time.equals("am") || time.equals("pm"))

  {

    validAnswerTwo="True";

  }


}
violet
  • 1
  • 4
  • 1
    Cannot reproduce. After wrapping this in a trivial class and defining `input` to be a `Scanner` referencing `System.in`, the code works as intended. – Silvio Mayolo May 05 '21 at 00:32
  • Can you post your output, it's likely you're calling the posted code block twice. Sidebar, why not use a Boolean for the `validAnswer` flag? – Philip Rollins May 05 '21 at 00:36
  • I have updated the code, please check it out. I can't use another boolean because my teacher want us to show a variety of ways to do while loop conditions – violet May 05 '21 at 00:40
  • 1
    If you write the code twice, then it's going to run twice. I don't understand where your confusion is coming from here. And on a side note, if your teacher things strings whose value is `"True"` or `"False"` is a remotely good way to represent Booleans, then you desperately need a new teacher. – Silvio Mayolo May 05 '21 at 00:41
  • how do I not make "Enter am or pm: " pop up twice? – violet May 05 '21 at 00:45
  • Now I understand what's going on. Check out the link above. – Silvio Mayolo May 05 '21 at 00:47
  • ill try it out. thanks for the suggestion – violet May 05 '21 at 00:52
  • it works. just had to change input.nextLine(); to input.next(); – violet May 05 '21 at 00:54
  • Curiously, this similar question has the same nextLine problem on the same sort of question. https://stackoverflow.com/questions/67392706/why-do-i-get-two-errors-when-comparing-strings-elapsed-time/67392866? – something May 05 '21 at 00:54
  • I still wouldn't use "True" or "False" string flags, use something like `while (!time.equals("am") && !time.equals("pm"))` and remove the flag all together. Might also be good to use `equalsIgnoreCase` so `'PM' == 'pm'`, just suggestions. – Philip Rollins May 05 '21 at 00:56

0 Answers0