Skip to content
Advertisement

Read next word in java

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?

Advertisement

Answer

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);
        }
    }
Advertisement