开发者

Check if a string is equal or substring of another

I am trying to check if one string is the same as another or maybe if it's a part of it with the code below:

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.index开发者_如何学编程Of(check);
            }//while
        }//while

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

But I get the error below:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:838)
    at java.util.Scanner.next(Scanner.java:1347)
    at results.Comparison.compare(Comparison.java:28)
    at results.Main.main(Main.java:42)

What is the problem? How can I make it work?


I think you need to use nextLine(), not next(). As in:

String check = queries.nextLine();

and:

String toCheck = folks.nextLine();

Because the default delimiter is whitespace, if you have a blank line at the end of the file (and maybe other things), there may not be a next(), even though hasNextLine() returned true. Always use the hasNext*() method corresponding to the next*() that you're using - (and vice versa ;-)).


The initialization of folks needs to be inside the outer loop, for example:

        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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜