Pregunta

I have a simple Do While loop using the Scanner function that is not working properly. The code should display a text prompting user to enter a string,user enters string, and then the program displays the same text again and prompting user to enter another string.

What the program is doing is it does display the correct message, user enters a string in, then it prompts user to enter a string without the text preceding the user input. After the user enters the text, it then works properly.

Looking at my code, I cannot see any reason for the program to prompt the user twice for their input without showing them the Text.

String userinput;
   Scanner sr = new Scanner(System.in);
   do{
     System.out.println("Enter a string for character classification: (EOF to end):");
      userinput = sr.nextLine();
   }while(sr.hasNext());

}
}
¿Fue útil?

Solución

Before you use nextLine(), you need to check whether there is a next line. You should probably use a regular while() loop for that reason, rather than a do/while.

Since it's a Scanner and the User may be continuously entering text, you may want to save that text as a String and put a loop outside the while() checking for the EOF message.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top