2

我正在尝试使用以下代码检查一个字符串是否与另一个字符串相同,或者它是否是其中的一部分:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;


public class Comparison {

    static void compare() throws FileNotFoundException {

        Scanner queries = new Scanner(new FileReader("./out.txt"));
        Scanner folks = new Scanner(new FileReader("./tal.txt"));
        int index1 = 0;
        while ( queries.hasNextLine() ){
            String check = queries.next();

            while (folks.hasNextLine()) {
                String toCheck = folks.next();
                index1 = toCheck.indexOf(check);
            }//while
        }//while

        System.out.println("Result: "+ index1);
    }
}

但我收到以下错误:

线程“主”java.util.NoSuchElementException 中的异常
    在 java.util.Scanner.throwFor(Scanner.java:838)
    在 java.util.Scanner.next(Scanner.java:1347)
    在 results.Comparison.compare(Comparison.java:28)
    在结果.Main.main(Main.java:42)

问题是什么?我怎样才能让它工作?

4

2 回答 2

2

我认为您需要使用 nextLine(),而不是 next()。如:

String check = queries.nextLine();

和:

String toCheck = folks.nextLine();

因为默认分隔符是空格,如果文件末尾有一个空行(可能还有其他内容),即使 hasNextLine() 返回 true,也可能没有 next()。始终使用与您正在使用的 next*() 相对应的 hasNext*() 方法 - (反之亦然;-))。

于 2011-09-20T16:30:37.757 回答
1

的初始化folks需要在外循环内部,例如:

        Scanner queries = new Scanner(new FileReader("./out.txt"));
        int index1 = 0;
        while ( queries.hasNextLine() ){
            String check = queries.next();
            Reader r = new FileReader("./tal.txt");
            try {
                Scanner folks = new Scanner(r);
                while (folks.hasNextLine()) {
                    String toCheck = folks.next();
                    index1 = toCheck.indexOf(check);
                    if (index1 >= 0) {
                        // Do something with index1 here?
                    }
                }//while
            } finally {
                r.close();
            }
        }//while
于 2011-09-20T16:43:53.307 回答