tryor
tryor

Reputation: 43

Java - find matching string from .text file

I want to find matching string from .text file. but using this code I can only get the matching string of the first line of the text file. it does not run to the other lines of the text file

Scanner scanner = new Scanner(file);

while (scanner.hasNextLine()) {

    System.out.println("Inside next line");
    String line = scanner.nextLine();
    System.out.println(line);
    String[] tokenarray = line.split(":");

    if (tokenarray[0].equals(id)) {
        System.out.println("match found");
        System.out.println(tokenarray[0]);
        customer = new Customer(tokenarray[0], tokenarray[1],
                tokenarray[2], tokenarray[3], tokenarray[4],
                tokenarray[5], tokenarray[6], tokenarray[7],
                tokenarray[8]);
                break;
        }
}

This code works only when is input id as tokenarray[0] value of the first line of the document. I want to search whole text document. not only the first line.

Upvotes: 0

Views: 529

Answers (2)

roeygol
roeygol

Reputation: 5028

It seems like when you will remove the break it will solve your problem.

Upvotes: 1

Martin Pfeffer
Martin Pfeffer

Reputation: 12627

    String line = "hello:world:hello:up";
    String[] tokenarray = line.split(":");
    for (String s : tokenarray) {
        System.out.print((s.contains("hello") ? "match" : "no match"));
        System.out.print(", ");
    }

output:

match, no match, match, no match,

Upvotes: 0

Related Questions