Read next word in java

Upvote picture Upvote · Jan 1, 2011 · Viewed 162.4k times · Source

I have a text file that has following content:

ac und
accipio annehmen
ad zu
adeo hinzugehen
...

I read the text file and iterate through the lines:

Scanner sc = new Scanner(new File("translate.txt"));
while(sc.hasNext()){
 String line = sc.nextLine();       
}

Each line has two words. Is there any method in java to get the next word or do I have to split the line string to get the words?

Answer

Christopher Tokar picture Christopher Tokar · Jan 1, 2011

You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.

You can just create a new Scanner object within your while statement.

    Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("translate.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }
    while (sc2.hasNextLine()) {
            Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) {
            String s = s2.next();
            System.out.println(s);
        }
    }