[英]Scanner nextLine() issues
我已经从事了一段时间的编程任务,该任务充当Scrabble词典。 该程序从用户处获取输入,并输出包含单词列表的文件,具体取决于用户从菜单中请求的内容。 我一直遇到的问题与Scanner.nextLine()有关。
我不太清楚为什么,但是出于某种原因,有时我必须按一次Enter键,然后我的代码才会接受我的输入并将其存储为变量。 本质上,我最终两次输入了输入。 我尝试在代码周围插入Scanner.nextLine()以“占用”空的enter /空格,但是它不起作用,而且我必须多次按Enter才能使它处理我想要的内容。
有人有什么建议吗? 我将不胜感激。
这是一些代码:
System.out.println("Enter the length of the word you are" + " searching for.");
int n = -1;
while(!(n >=0)) {
if(in.hasNextInt())
n = in.nextInt();
else {
System.out.println("You have not entered a valid number.
Please enter a real number this time.");
in.nextLine();
}
}
in.nextLine();
System.out.println("Enter the first letter of the words" + " you are searching for.");
String firstLetter = "";
while(!(firstLetter.length() == 1)) {
if(in.nextLine().length() > 1) {
System.out.println("You have not entered a valid letter.
Please press enter and enter only one real letter.");
}
else if(in.hasNextInt()) {
System.out.println("Do not enter a number. Please enter one real letter.");
}
else {
in.nextLine();
firstLetter = in.nextLine();
break;
}
}
最后,我必须按一次enter键,然后输入才能使其存储任何内容到firstLetter变量中。 我认为这与nextLine()的性质有关,因为使用nextInt()的条件没有问题。
这是因为您同时使用了nextLine()和nextInt(),这是因为nextLine()正在搜索新行(输入),并且如果通过System.in输入了任何整数,nextInt将自动停止搜索。
经验法则:只需使用Scanner.nextLine()作为输入,然后通过Integer.parseInt(string)等相应地从Scanner.nextLine()转换您的字符串。
我认为您对太多的nextLine
过度补偿。 您可能想要这样做一次以在输入int之后清除该行,例如,清除换行符,但是第二次在这里只是吸收了额外的输入行:
System.out.println("You have not entered a valid number. Please enter a real number this time.");
in.nextLine();//first time
}
}
in.nextLine();//this second time is unnecessary.
同样的事情发生在您重复使用的地方:
in.nextLine();
firstLetter = in.nextLine();
break;
您应该只添加一个额外的in.nextLine()
立即输入之间nextSOMETHINGELSE()
和另一nextLine()
编辑:
此外,请注意, 每当调用in.nextLine()
,您都会吸收一行输入。 例如,此行应固定:
if(in.nextLine().length() > 1){
因为它读入一行, 用完,然后检查该行(现在用完了)是否足够长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.