Reputation: 25
I have a txt file that has:
it was the best of times it was the worst of times
it was the age of wisdom it was the age of foolishness
it was the epoch of belief it was the epoch of incredulity
it was the season of light it was the season of darkness
it was the spring of hope it was the winter of despair
and I want to put them into 1 arraylist, each word separated by commas. so far, I have this:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class arraylist{
public static void main(String[] args) {
try {
Scanner s = new Scanner(new File("tinyTale.txt"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
System.out.println(list);
}
s.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
as output, I am getting:
[it]
[it, was]
[it, was, the]
[it, was, the, best]
[it, was, the, best, of]
[it, was, the, best, of, times]
[it, was, the, best, of, times, it]
[it, was, the, best, of, times, it, was]
[it, was, the, best, of, times, it, was, the]
[it, was, the, best, of, times, it, was, the, worst]
[it, was, the, best, of, times, it, was, the, worst, of]
[it, was, the, best, of, times, it, was, the, worst, of, times]
[it, was, the, best, of, times, it, was, the, worst, of, times, it]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom, it]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom, it, was]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom, it, was, the]
...and continues with the rest of the contents, so it is starting over every time there is a space...so the very last thing it prints out is what I need. Any help would be appreciated!
Upvotes: 0
Views: 49
Reputation: 53829
That is just because your print the full content of the list at each iteration of the loop, before the loop is complete.
If you just want to print the final content of the list, print after the loop:
while (s.hasNext()){
list.add(s.next());
}
System.out.println(list);
Upvotes: 3
Reputation: 1115
This is because your println statement is within the loop. Move System.out.println(list);
outside the while
loop to see the desired output.
Upvotes: 3