0

I want to make an array of size 150 of the class Info

public class Info {
    int Group;
    String Name;
}

But I have the exception occur after

 public class Mover {
        static Info[] info=new Info[150];
            public static void main(String[] args) {
            info[0].Group=2;//I get error here
        }
}

I'm not sure if there is a better way to do what a want to do, but I don't want to use a multidimensional array. I'm simply trying to add information to the group, so I'm confused.

Kick Buttowski
  • 6,631
  • 13
  • 35
  • 57
Avionix
  • 47
  • 8

3 Answers3

1

doing new Info[150] simply instantiates an array of size 150. All elements within the array have not been instantiated and are therefore null.

So when you do info[0] it returns null and you're accessing null.Group.

You have to do info[0] = new Info() first.

Ori Lentz
  • 3,670
  • 6
  • 21
  • 28
0

This static Info[] info=new Info[150]; is creating an array of 150 objects of type info pointing to NULL. You have to do this to get this working

for(int i = 0; i< 150; i++) info[i] = new Info();

Then you can use these objects

Kick Buttowski
  • 6,631
  • 13
  • 35
  • 57
0

Go through some tutorial first Java Arrays

You need to initialize the array elements like:

info[0] = new Info()

From JLS 10.6. Array Initializers

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

Andy Turner
  • 131,952
  • 11
  • 151
  • 228
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100