Skip to content
Advertisement

Can’t use array of objects

I have a Main and a Cars classes, and I am trying to create an array of Cars and have it like this:

public class Cars {

    protected String brand;
    protected int price;
    protected Cars[] list;
    Scanner keyboard;
    
    public Cars() {
        keyboard=new Scanner(System.in);
    }
    
    public void carList() {
        int nv;
        System.out.println("number of cars");
        nv=keyboards.nextInt();
        Cars [] list = new Cars[nv];
        ...
    }

then I have this for:

for(int i=0; i<list.length;i++){
    list[i].brand=keyboard.next();
    list[i].price=keyboard.nextInt();
}

to try and fill it but I get this error:

Cannot assign field "brand" because "list[i]" is null

Can you help me pointing what I’m doing wrong please?

Advertisement

Answer

You create Cars array, as:

Cars[] list = new Cars[nv];
/* two smells here:
   1. Cars (plural) as a type, and having array of Cars objects.. that is Cars of cars;
   2. don't name arrays as list.. lists are another type.
*/

but you never put any car instance into that array.

Afterwards, with:

list[i].fieldName

you are trying to fetch the ith element from the list array and access its field, but you have nulls in your array (which is the default value array of reference type is initialized with), therefore, fields brand and price will not be resolved as you’re accessing them on the null reference.

Instead, you should first create an object(s) and put that(those) into your array.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement