I need help moving numbers from an ArrayList (listInt) to three different arrays (iN, v and w).
`import java.io.; import java.util.;
public class ReadingFileThree {
public static void main(String[] args) throws FileNotFoundException{
//Try Catch for error catching
try{
int n = 0,C; //Number of items and maximum capacity
int iN[] = null,v[] = null,w[] = null; //Item number, weights and values of items
int V[][]; //Table to store results of sub-problems
//Calling inbuilt methods to open the file we wish to read
Scanner s = new Scanner(new File("easy.20.txt"));
//An ArrayList is used because it increases in size dynamically
ArrayList<Integer> listInt = new ArrayList<Integer>(); //Int ArrayList
//Method for adding the numbers in the file to the Int ArrayList
while (s.hasNextLine()){
listInt.add(s.nextInt());
n++;
}
//Closing the file. Need to be done or we get errors and memory leaks
s.close();
//Hold the maximum capacity of the knapsack (The last int in the file)
C = listInt.get(n-1);
for(int i = 0; i < n; i++){
iN[i] = listInt.get(i+1); //item number
v[i] = listInt.get(i+2); //weight of item
w[i] = listInt.get(i+3); //value of item
i = i+2;
}
//Untested next stage
//V = new int[n+1][C+1]; //initialising the table to hold results
//for(int i = 0; i <= C; i++) V[0][i] = 0;
//}
//Print out commands for testing purposes
System.out.println("All the numbers in the ArrayList are: " + listInt);
System.out.println("n = " + n);
System.out.println("C = " + C);
}
catch(Exception e) {
System.out.println("File not found yo");
}
}
} `
The problem appears in the for loop. It gives an Error when trying to use an array in there. The error is: null pointer access problem
The file being read looks like this.
4
1 16 34
2 3 30
3 46 34
4 42 47
10
- The number on the first line is the Number of Items
- The number on the last line is the Capacity of the Knapsack
- The four lines in between show the: Item Number - Value - Weight
I haven't used Java much, Please help.