while 循环不会中断 (JAVA)
While loop won't break (JAVA)
这是代码:
Scanner reader = new Scanner(System.in);
while (true) {
System.out.print("Type a word: ");
String word = reader.next();
if (word.isEmpty()) {
break;
}
}
即使我在 if
语句中有 break;
,即使在我输入空白字符串后它仍然运行。我错过了什么?
你怎么知道你的字符串是空的?您没有输入任何内容就按了回车键?你怎么知道 reader 没有将新行字符放入字符串中导致它不为空?读完后立即打印读入字符串的长度;您可能很快就会发现为什么 isEmpty() returns false..
假设"reader"是一个Scanner实例,试试
String word = reader.nextLine();
这样,当您输入空字符串时,扫描仪将 return。
这是代码:
Scanner reader = new Scanner(System.in);
while (true) {
System.out.print("Type a word: ");
String word = reader.next();
if (word.isEmpty()) {
break;
}
}
即使我在 if
语句中有 break;
,即使在我输入空白字符串后它仍然运行。我错过了什么?
你怎么知道你的字符串是空的?您没有输入任何内容就按了回车键?你怎么知道 reader 没有将新行字符放入字符串中导致它不为空?读完后立即打印读入字符串的长度;您可能很快就会发现为什么 isEmpty() returns false..
假设"reader"是一个Scanner实例,试试
String word = reader.nextLine();
这样,当您输入空字符串时,扫描仪将 return。