扫描仪nextLine()问题

时间:2014-04-21 01:32:21

标签: java java.util.scanner

我一直在编写一个编程任务,现在作为一个Scrabble字典。程序从用户获取输入并输出带有单词列表的文件,具体取决于用户从菜单中请求的内容。我遇到的问题与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;
    }
}

在此结束时,我必须按Enter键一次然后输入以使其在变量firstLetter中存储任何内容。我认为它与nextLine()的性质有关,因为使用nextInt()的条件没有问题。

2 个答案:

答案 0 :(得分:3)

这是因为您同时使用了nextLine()和nextInt(),正在进行的是nextLine()正在搜索新行(输入),nextInt将自动停止搜索是否通过System.in键入任何整数。

经验法则:只需使用Scanner.nextLine()作为输入,然后通过Integer.parseInt(string)等将Scanner.nextLine()中的字符串转换为

答案 1 :(得分:0)

我认为你对过多的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){

因为它在一行中读取,使用它,然后检查该行(现在已用完)是否足够长。

相关问题