Reputation: 57
What I tried to achieve is to separate the text input into groups when there's an empty line. The way I wanted to achieve this is by adding the lines to ArrayList< String > temp until there's an empty line. After that I added temp to ArrayList<ArrayList< String >> group. But It seems like It only adds the last temp values to group. I can't see why. Here's the code:
public static void main(String... args) throws IOException {
List<String> data = new ArrayList<>();
File f = new File("input6.txt");
try (Scanner sc = new Scanner(f)) {
while (sc.hasNext()) {
data.add(sc.nextLine());
}
} catch(FileNotFoundException e) {
e.printStackTrace();
}
List<List<String>> group = new ArrayList<>();
List<String> temp = new ArrayList<>();
for (String line : data) {
temp.add(line);
if (line.trim().isEmpty()) {
group.add(temp);
temp.clear();
}
}
}
Upvotes: 3
Views: 144
Reputation: 196
When you are adding the temp ArrayList to group it is not creating a new list but using the reference of the temp list. Hence when you clear the temp list the group values also get cleared so you will have to store a copy of temp into the group arraylist as below.
public static void main(String... args) throws IOException {
List<String> data = new ArrayList<>();
try {
File f = new File("input6.txt");
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
data.add(sc.nextLine());
}
} catch(FileNotFoundException e) {
e.printStackTrace();
}
List<List<String>> group = new ArrayList<>();
List<String> temp = new ArrayList<>();
for (String line : data) {
temp.add(line);
if (line.trim().isEmpty()) {
group.add(new ArrayList<>(temp));
temp.clear();
}
}
}
Upvotes: 1
Reputation: 18245
Your problem is you clear the temp list, because when you add it the result, it's been added by a reference. You have to add a copy to the result.
public static void main(String... args) throws FileNotFoundException {
File file = new File("input6.txt");
List<List<String>> groups = readFile(file);
}
public static List<List<String>> readFile(File file) throws FileNotFoundException {
List<List<String>> groups = new ArrayList<>();
List<String> group = new ArrayList<>();
try (Scanner scan = new Scanner(file)) {
while (scan.hasNext()) {
String line = scan.nextLine();
if (line.trim().isEmpty()) {
if (group.isEmpty())
continue;
groups.add(group);
group = new ArrayList<>();
} else
group.add(line);
}
if (!group.isEmpty())
groups.add(group);
}
return groups;
}
Upvotes: 1
Reputation: 51393
The problem is that you are always clearing the list (i.e., temp.clear();
) that you have added to the list group
. Instead of reusing the same reference, just reassign the temp
to a new list. Do the following instead:
ArrayList<ArrayList<String>> group = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>();
for(String line : data) {
temp.add(line);
if(line.trim().isEmpty()) {
group.add(temp);
temp = new ArrayList<String>();
}
}
Upvotes: 4