ArrayList contents Out of Scope, and deleted, after a While Loop in Java
I'm attempting to save a list of lists to an ArrayList using a while loop which is looping over the lines in a scanner. The scanner is reading a 12 line text file of binary. The list of list (ArrayList) is successfully created, but as soon as the while loop terminates the variable ArrayList is empty and an empty list of lists is returned. I also tested the code by declaring a counter at the same time I declare the list of lists and the counter is incremented in the while loop and retains the data after the loop.
I'm still very new to coding! Thank you in advance.
public static void main(String[] args) throws Exception{
try {
readFile();
data = dataPrep();
}
catch (Exception e) {
e.printStackTrace ();
}
}
public static void readFile() throws FileNotFoundException {
try {
File inputtxt = new File("test.txt");
scanner = new Scanner(inputtxt);
}
catch (FileNotFoundException error) {
System.out.println(error);
}
}
public static ArrayList<ArrayList> dataPrep(){
ArrayList<ArrayList> allBinaryNumbers = new ArrayList<ArrayList>();
ArrayList<Integer> singleBinaryNumber = new ArrayList<Integer>();
int counter = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
char[] charLine = line.toCharArray();
for (char numb : charLine){
singleBinaryNumber.add(Integer.parseInt(String.valueOf(numb)));
}
allBinaryNumbers.add(singleBinaryNumber);
System.out.println(allBinaryNumbers);
singleBinaryNumber.clear();
counter++;
}
System.out.println(allBinaryNumbers);
System.out.println(counter);
return allBinaryNumbers;
}
My test.txt is this
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
Solution 1:
You are reusing the same singleBinaryNumber
which you clear after you finish populating it. Remember, this is a reference (pointer) which means you are adding the same list rather than new lists on each iteration.
You code should be something like this:
public static ArrayList<ArrayList> dataPrep(){
ArrayList<ArrayList> allBinaryNumbers = new ArrayList<ArrayList>();
int counter = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
char[] charLine = line.toCharArray();
ArrayList<Integer> singleBinaryNumber = new ArrayList<Integer>(); // create a new list for each iteration
for (char numb : charLine){
singleBinaryNumber.add(Integer.parseInt(String.valueOf(numb)));
}
allBinaryNumbers.add(singleBinaryNumber);
System.out.println(allBinaryNumbers);
// singleBinaryNumber.clear(); <-- remove this line
counter++;
}
System.out.println(allBinaryNumbers);
System.out.println(counter);
return allBinaryNumbers;
}