0

I started learning Java and have small problem. I have classes Point and abc:

static class Point
    {
        int x;
        int y;
        Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

static class abc
    {
        abc() 
        {
            Scanner s = new Scanner(System.in);
            Point[] p = new Point[2];
            for (int i = 0; i < 2; ++i) {
                p[i].x = s.nextInt();
                p[i].y = s.nextInt();
            }
        }
    }

But initialization in class abc doesn't work. When I try to write first number it gives:

   Exception in thread "main" java.lang.NullPointerException

    at main$abc.<init>(main.java:91)

    at main.main(main.java:99)

What should I do to make it work?

FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
Niko13
  • 9
  • You should solve the NPE. what line is it that throws it? – Stultuske Mar 29 '16 at 10:57
  • before you acces `p[i]` you should initialize each instance of `Point` in the array first as `p[i] = new Point(x,y)`. – SomeJavaGuy Mar 29 '16 at 10:58
  • 1
    Creating an array of references doesn't create objects references as as well. To see this you can use your debugger in your IDE to understand what is happening when this error occurs. – Peter Lawrey Mar 29 '16 at 11:01

1 Answers1

3

You only created the array of the Points, not the actual Points within the array.

Change

p[i].x = s.nextInt();
p[i].y = s.nextInt();

to

p[i] = new Point(s.nextInt(), s.nextInt());

or

int x = s.nextInt();
int y = s.nextInt();
p[i] = new Point(x, y);
gustf
  • 1,959
  • 13
  • 20