简体   繁体   中英

Null pointer exception when trying to parse array (java)

I'm getting a null pointer exception when I try to parse a string array index. How do I fix this? Thanks

public class studentclass {
public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    String[][] student = new String[10][];
    Double[][] results = new Double[10][];
    Double[] total = new Double[10];
    String tableln = "";

   for(int index = 0; index < student.length; index++){
    System.out.println("\nPlease enter student " + (index+1) + "'s details");
    String userinput = scan.nextLine();
    student[index] = userinput.split(",");

    //converts string array in to double array but receiving null pointer exception
    results[index][0] = Double.parseDouble(student[index][2]); 
    results[index][1] = Double.parseDouble(student[index][3]);
    results[index][2] = Double.parseDouble(student[index][4]);
    results[index][3] = Double.parseDouble(student[index][5]);
    total[index] = (results[index][0]*0.1+results[index][1]*0.4+
                    results[index][2]*0.3+results[index][3]*0.2);

Looks like results[index] needs to be initialized. You allocated memory for results[0..n] with new, but not results[index][0...n] .

If you're always storing four values, add something like:

results[index] = new Double[4];

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