【发布时间】:2014-04-21 01:32:20
【问题描述】:
一段时间以来,我一直在从事一项充当拼字游戏词典的编程任务。该程序从用户那里获取输入并输出一个包含单词列表的文件,具体取决于用户从菜单中请求的内容。我遇到的问题与 Scanner.nextLine() 有关。
我不确定为什么,但出于某种原因,有时我必须按一次回车,然后我的代码才会接受我的输入并将其存储为变量。本质上,我最终输入了两次。我尝试在代码周围插入 Scanner.nextLine() 以“占用”空的输入/空格,但它不起作用,我必须多次按 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;
}
}
最后,我必须按回车键一次,然后输入才能将任何内容存储在变量 firstLetter 中。我认为这与 nextLine() 的性质有关,因为使用 nextInt() 的条件没有问题。
【问题讨论】:
-
如果您希望人们自愿花时间帮助您解决问题,那么您至少应该努力正确地格式化您的代码。
-
谢谢,我很抱歉老兄,我按了八次,它仍然无法格式化。 Control+K 也做了插孔。不过万岁还是仇杀。
-
制表符不是你的朋友 :) 下次尝试只使用空格。