I have a text file that has following content:
JavaScript
x
ac und
accipio annehmen
ad zu
adeo hinzugehen
I read the text file and iterate through the lines:
JavaScript
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.
JavaScript
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);
}
}