Java while循环搜索中的NoSuchElementException

Java while循环搜索中的NoSuchElementException,java,Java,嗨,这是我代码的一部分,当我试图运行这个程序时,它总是抛出一个java.util.NoSuchElementException。行内字符串a=sub.next();。请告诉我如何解决这个问题好吗 while(s.hasNextLine()) { String line = s.nextLine(); Scanner sub = new Scanner(line); String a = sub.next(); if(a.equalsIgnoreCase(word)

嗨,这是我代码的一部分,当我试图运行这个程序时,它总是抛出一个java.util.NoSuchElementException。行内字符串a=sub.next();。请告诉我如何解决这个问题好吗

while(s.hasNextLine())
{
    String line = s.nextLine();
    Scanner sub = new Scanner(line);
    String a = sub.next();
    if(a.equalsIgnoreCase(word))
    {
        replyMessage = line;
        break;
    }
    else if(word.equals(" ") || word.isEmpty())
    {
        replyMessage = "please give a word!";                   
    }
    else
    {
        replyMessage = "Can not find this word";                
    }
}

问题在于下面的代码

String line = s.nextLine();
Scanner sub = new Scanner(line);
String a = sub.next();
您需要检查sub是否有下一个元素,就像您为s所做的一样

添加类似以下内容的if语句

if(sub.hasNext()){
    String a = sub.next();

此外,您还需要做一些事情,以防它不存在,因为您当前的程序没有下一行

如果我们可以看到s是如何填充的,那么就更容易提供帮助

 if(word.equals(" ") || word.isEmpty())
逻辑上等同于

if(word.trim().isEmpty())
而且打字和理解更简单

编辑

顺便说一句,您只查看每行中的第一个元素。您将需要一个嵌套的循环来查看行中的每个元素,这也将处理“未找到元素”问题

while(s.hasNextLine())
{
String line = s.nextLine();
Scanner sub = new Scanner(line);

while(sub.hasNext())
{
String a = sub.next();
if(a.equalsIgnoreCase(word))
{
    replyMessage = line;
    break;
}
else if(word.equals(" ") || word.isEmpty())
{
    replyMessage = "please give a word!";                   
}
else
{
    replyMessage = "Can not find this word";                
}
}
}

如果
line
为空,则您的
sub.next()
将抛出所述异常,因为缓冲区中没有可读取的令牌。@Nick我编辑了我以前的答案,第一个答案是错误的谢谢,我按照您的建议解决了这个问题。非常感谢。