Can Java object arrays initialize elements as non-null values?

前端 未结 1 1379
太阳男子
太阳男子 2021-01-18 19:08

I\'m pretty new at Java and I\'m having a tough time figuring out how to fix this null pointer exception that has been troubling me.

I know where the problem occurs

相关标签:
1条回答
  • 2021-01-18 19:41

    Your entire array is null ! remember , arrays are never automatically initialized in java, unless they are arrays of ints,floats,doubles, or booleans.

    Scanner input = new Scanner//System.in.Scanner;
    
    Account[] atm = new Account[10];
    
    for (int i = 0; i < 10; i++){
        **atm[i] = new Account();**
        atm[i].setId(i);
        atm[i].setBalance(100.00);
    }
    

    When you're declaring arrays that hold objects, read it as, "I'm creating an array that will hold 'x' objects." (correct), and then proceed to instantiate those objects

    ...as opposed to...

    "I'm creating an array with 'x' objects in it." (incorrect) since there aren't any objects in there yet because they haven't been created.

    0 讨论(0)
提交回复
热议问题