当要求用户输入时如何打破 while 循环?
当用户输入空行而不是国家/地区时,我需要尝试打破 while 循环。这是我到目前为止所做的代码,它似乎并不想结束询问国家/地区的循环:
public void userInterface()
{
// interactive interface
Scanner input = new Scanner(System.in);
System.out.println("Enter the date:");
String date = input.nextLine();
ArrayList<String> countries = new ArrayList<String> ();
System.out.println ("Enter the list of countries (end with an empty line):");
while (input.hasNext()) {
String country = input.nextLine();
if (country.isEmpty()){
break;
}
char c = country.charAt(0);
if (Character.isUpperCase(c)==false){
System.out.println ("Type with Capital Letter!");
} else {
countries.add(country);
}
}
}
用户输入应如下所示:
Enter the date:
2022-02-17
Enter the list of countries (end with an empty line):
Norway
Suriname
South Namibia
i need to try to break the while loop when a user enters an empty line instead of countries. Here is the code I have done so far and it does not seem to want to end the loop of asking for countries:
public void userInterface()
{
// interactive interface
Scanner input = new Scanner(System.in);
System.out.println("Enter the date:");
String date = input.nextLine();
ArrayList<String> countries = new ArrayList<String> ();
System.out.println ("Enter the list of countries (end with an empty line):");
while (input.hasNext()) {
String country = input.nextLine();
if (country.isEmpty()){
break;
}
char c = country.charAt(0);
if (Character.isUpperCase(c)==false){
System.out.println ("Type with Capital Letter!");
} else {
countries.add(country);
}
}
}
the user input should look as follows:
Enter the date:
2022-02-17
Enter the list of countries (end with an empty line):
Norway
Suriname
South Namibia
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您检查
hasNext()
但应该检查hasNextLine()
。但是,请不要执行以下任一操作:
Your checking for
hasNext()
but should be checking forhasNextLine()
.However, don’t do either:
您还可以在 do while 循环之前设置一个空的国家/地区字符串,并检查国家/地区最终是否不为空:
You could also set an empty country string before a do while loop and check for the the country not being empty in the end: