简体   繁体   English

使用扫描仪执行While While循环无法正常工作

[英]Do While Loop using Scanner not properly working

I have a simple Do While loop using the Scanner function that is not working properly. 我有一个使用“扫描器”功能的简单“ Do While”循环,该循环无法正常工作。 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());

}
}

Before you use nextLine() , you need to check whether there is a next line. 在使用nextLine()之前,需要检查是否存在下一行。 You should probably use a regular while() loop for that reason, rather than a do/while. 出于这个原因,您可能应该使用常规的while()循环,而不是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. 由于它是扫描程序,并且用户可能会不断输入文本,因此您可能需要将该文本另存为字符串,并在while()外部放置一个循环,以检查EOF消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM