简体   繁体   中英

Null pointer exception for creating array of objects in java

I have checked almost all kinds of declarations for an array of objects. Please suggest the required changes.This code gives me a null pointer exception as follows:

Exception in thread "main" java.lang.NullPointerException at objarray.main(objarray.java:33)

import java.util.*;
class Prod {
    private int    pno, pcost;
    private String pname;

    void accept() {
        Scanner sc = new Scanner( System.in );
        System.out.println( "Enter pno" );
        pno = sc.nextInt();
        System.out.println( "Enter pname" );
        pname = sc.next();
        System.out.println( "Enter pcost" );
        pcost = sc.nextInt();
    }

    void print() {
        System.out.println( pno + "\t" + pname + "\t" + pcost );
    }
}

class objarray {
    public static void main( String[] args ) {
        int i;
        Prod[] p = new Prod[3];
        for( i = 0; i < 3; i++ )
            p[i].accept();
        for( i = 0; i < 3; i++ )
            p[i].print();
    }
}

You need to initialize the elements of your array:

Prod[] p = new Prod[3];
for(i = 0;i<3;i++)
    p[i] = new Prod(); // added this line
    // rest of code

The statement Prod[] p = new Prod[3]; just allocates space for the references to Prod objects - it doesn't create them.

    Prod[] p = new Prod[3];
    for(i = 0;i<3;i++){
        p[i] = new Prod(); // this will assign in each
// rest your logic.

    }

hope that helps.

初始化数组中的元素,以避免出现空指针异常,以获得清晰的画面,尝试使用eclipse调试器,在该调试器中您将知道存在空值的位置,并且可以轻松解决这些问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM