扫描仪未返回任何线路

时间:2015-02-06 03:09:47

标签: java java.util.scanner

我运行时遇到“No line found”异常。这是我项目中唯一一个给我这个错误的方法。每个其他方法使用相同的代码和参数,但没有一个遇到此错误。

有问题的方法是findLargestPalindrome()

异常

 Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at cs1410.TestClass.findLongestPalindrome(TestClass.java:51)
    at cs1410.TestClass.main(TestClass.java:12)


import java.util.Scanner;
import java.util.StringTokenizer;

public class TestClass 
{
    static Scanner test = new Scanner("Hello world! This is my program.");

    public static void main(String[] args)
    {
        System.out.println(findLongestPalindrome(test));
    }

    public static boolean isPalindrome(String s)
    {
        if(s.length() == 0)
        {
            return false;
        }

        int stringLength = s.length() -1;

        if(stringLength == 0)
        {
            return false;
        }

        for(int i = 0; i < stringLength; i++)
        {
            if(s.charAt(i) == s.charAt(stringLength))
            {
                stringLength--;
            }
            else
            {
                return false;
            }
        }
        return true;
    }

    public static String findLongestPalindrome(Scanner s)
    {
        int pLength = 0;
        String largestPalindrome = "";
        String currentToken;

        if(s.nextLine().length() > 0)
        {
            String input = s.nextLine();
            StringTokenizer inputTokens = new StringTokenizer(input);

            while(inputTokens.hasMoreTokens())
            {
                currentToken = inputTokens.nextToken();

                if(isPalindrome(currentToken) == true)
                {
                    if(currentToken.length() > pLength)
                    {
                        pLength = currentToken.length();
                        largestPalindrome = currentToken;
                    }   
                }
            }
        }
        else
        {
            return null;
        }
        return largestPalindrome;
    }
}

1 个答案:

答案 0 :(得分:2)

当您访问Scanner中的findLongestPalindrom()时,Scanner中只有一行(&#34; Hello world!这是我的程序。&#34;)并且您试图读取两行(你丢弃第一行),

if(s.nextLine().length() > 0) // <-- reads the line and advances
{
    String input = s.nextLine(); // <-- there isn't another line.

应该是

String input = s.nextLine();
if (!input.isEmpty()) {
  // ...

String input = s.nextLine();
if (input.length() > 0) {
  // ...

每次拨打Scanner.nextLine()时,都会消耗该线路。