开发者

Exception in thread "main" java.lang.NullPointerException [duplicate]

This question already has answers here: What is a NullPointerException, and how do I fix it? (12 answers) Closed 6 years ago.

I am a beginner in java programming. I am trying to develop a program but when I ran my program which is posted below and it came back with this error:

Exception in thread "main" java.lang.NullPointerException at dist.main(dist.java:13)

import java.lang.Math;
class Point { 
    int x;   int y;
}

public class dist {
    public static void main(String[] args) {    
        Point[] pt = new Point[3];
        pt[0].x = 40; pt[0].y开发者_运维问答 = 40;
        pt[1].x = 40; pt[1].y = 30;
        pt[2].x = 26; pt[2].y = 30;

for(int i = 0 ;i < pt.length ; i ++){
         pt[i] = new Point();
}


        int ux = pt[0].x - pt[1].x;
        System.out.println("ux:" + ux);     
    }
} 


by following line you are just creating an array of 3 reference which has null value by default

point []pt=new point [3];

you need to initialize each reference to the object using new as shown below

 for(int index = 0 ;index < pt.length ; index ++){
       pt[index] = new Point();
 }


That is because you create the array that can hold 3 points, but you don't create the points themselves before trying to access them.

You have to do:

    point []pt=new point [3];
    pt[0] = new point();
    pt[0].x=40; pt[0].y=40;
    pt[1] = new point();
    pt[1].x=40; pt[1].y=30;
    pt[2] = new point();
    pt[2].x=26; pt[2].y=30;

But while you're learning, you should get used to the java code style. Classes start with capital letters, use correct indention and also have a look at constructors as soon as possible. E.g., adding an constructor like

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

to your Point class would give you the possibility to init your points like

    Point[] points = new Point[] { new Point(40,40), new Point(40,30), new Point(26,30) };

Also this line

    int ux=pt[n].x-pt[1].x;

should not even compile with the n not being declared anywhere.

Have fun learning Java!

PS.: creating the points in a loop as suggested by the other answers is of course the more DRY way to do it.


Creating an array of objects does not create objects in the array.

You need to do this first before accessing the array elements:

for (int i = 0; i < point.length; i++) {
  pt[i] = new point();
}


pt[0].x=40; pt[0].y=40; pt array has null and you are trying to get the 0th position record and assigned it. that's way it gives null pointer exception, if you wish then go through by the below given line of code

point p=new point();
pt[0]=p
pt[0].x=40; pt[0].y=40; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜