首页 > 解决方案 > NoSuchElementException:使用 hasNextLine 找不到行

问题描述

我已经包含了一个 hasNextLine 异常,但我仍然收到 NoSuchElementException 错误

我正在创建一个从文件扫描的回文程序。我可以让它从文件中扫描,但它只返回非回文词,并返回 NoSuchElementException: No Line Found 的错误,即使我已经包含了一个 hasNextLine。

case 3:
            System.out.println("Palindrome problem.");

    while (input.hasNextLine()) {          
        String text, reverse = input.nextLine();            
        text = input.nextLine();             
        int length = text.length();   
        for ( int i = length - 1; i >= 0; i-- )  
        reverse = reverse + text.charAt(i);  
            if (text.equals(reverse))  
            System.out.println(text + "is a palindrome.");  
                else  
                System.out.println(text + "isn't a palindrome.");    
    }
            break;

我希望代码读取整个文件并返回回文和非回文词

标签: javanosuchelementexception

解决方案


这是因为您在input.nextLine()这里调用了两次:

String text, reverse = input.nextLine();            
text = input.nextLine();

执行时text = input.nextLine();,该行已被消耗。


推荐阅读