Click here to Skip to main content
15,900,724 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Every time I run my code, i get this error:

Exception in thread "main" java.lang.NullPointerException

What I have tried:

import java.util.Scanner;
public class JaggedArray 
{

	public static void main(String[] args)
	{
		
		int[][] jArr; 
		jArr = new int[25][];
		System.out.println("Please enter number of students:");
		Scanner sc = new Scanner(System.in);
		int students = sc.nextInt();
		for (int i = 0; i < students; ++i)
		{
			System.out.println("How many grades does student " + (i+1) + " have:");
			int gradeNum = sc.nextInt();
			jArr[i] = new int[gradeNum];
			for (int j = 0; j < gradeNum; ++j)
			{
				System.out.println("Please enter grade " + (j+1) + ":");
				jArr[i][j] = sc.nextInt();
			}
		}
		System.out.println("Your array is: ");

                //It shows an error in my method calling
		displayArray(jArr);
		
	
	public static void displayArray(int[][] jArr)
	{

		for(int i = 0; i < jArr.length; i++)
		{
                        //It shows an error on this nested for loop
			for(int j = 0; j < jArr[i].length; j++)
			{
				System.out.print(jArr[i][j] + " ");
			}
			System.out.println();
		}
	}
}
Posted
Updated 6-Oct-18 11:27am

1 solution

Quote:
jArr = new int[25][];
The above line is the culprit. Move down a bit the array definition:

Java
//...
Scanner sc = new Scanner(System.in);
int students = sc.nextInt();
jArr = new int[students][]; // <- this is the right place (because you know 'students')
for (int i = 0; i < students; ++i)
//..
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900