0

I need to add a randomly generated number to an object state, keeping track of where in the array the object is by a count (acc_count) that is written to a text file each time a new object is added to the array. After the random number is added to the array as (.set/.getUserID) I want to print all userIDs in the array of objects, however I get the error [java.lang.NullPointerException]. Why is this happening?

public class Test {

public static int acc_count = 0;

public static void main(String[] args) throws IOException{

    Accounts[] account = new Accounts[2000];
    ArrayList<Integer> list = new ArrayList<Integer>();

    for (int i = 1000; i < 9999; i++) {
        list.add(new Integer(i));
    }

    Collections.shuffle(list);

    FileReader fr = new FileReader("Instance Counter.txt");
    BufferedReader br = new BufferedReader(fr);
    FileWriter fw = new FileWriter("Instance Counter.txt", true);

    String line = br.readLine();
    acc_count = Integer.parseInt(line);
    acc_count++;
    String l = String.valueOf(acc_count);

    PrintWriter pw = new PrintWriter("Instance Counter.txt");
    pw.close();

    fw.write(l);
    fw.close();  

    account[acc_count-1] = new Accounts();
    account[acc_count-1].setUserID(list.get(acc_count));


        for (int f = 0; f < account.length; f ++){
            System.out.println(account[f].getUserID());

        }


}

}

  • do you know what triggers an NPE? – Stultuske Sep 18 '17 at 09:21
  • 1
    Your last loop probably needs to take `acc_count` into account (that rhymes!) or have a null check. – Thilo Sep 18 '17 at 09:23
  • 2
    You set one single `Accounts` item in that array and then you try to interate over the whole array and call `getUserID()` on each item. How should that work when you expect more than one item in the array? – Tom Sep 18 '17 at 09:23
  • Only the last element of your array is filled. All the other ones are still `null`. – QBrute Sep 18 '17 at 10:47

0 Answers0