/*I need to store some information in a ragged 2d array. So i want this program to take in ex. 3 names, and for each name i want the array to store a number of courses for each name. ex. name anders have take 3 courses, oop, intP , appDesign.
I have tried to make it proces this information into the array with 2 for loops, but there is somthing wrong with the loops. Hope anybody can help or give me a clue. Regards
package assignment10;
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
System.out.println("Enter the number of students you want to enter into the database");
Scanner number = new Scanner(System.in);
int numberStudents = number.nextInt();
int[] numberOfStudents = new int[numberStudents];
for (int i = 0; i < numberOfStudents.length; i++) {
numberOfStudents[i] = i+1; // here i avoid the length 0
}
System.out.println("you have entered " + numberStudents + " number of students");
for (int j = 0; j < numberOfStudents.length; j++) {
System.out.println(numberOfStudents[j]);
}
// This is here im having trouble Where in the for loops have i made the //mistake
String [][] nameCourseArray =new String [numberOfStudents.length][];
Scanner name = new Scanner(System.in);
Scanner courseName = new Scanner ( System.in);
for( int i = 0 ; i < numberOfStudents.length; i++ ){ // maybe here
System.out.println("enter name of student");
nameCourseArray[0][0] = name.nextLine();
for( int j = 0;j < nameCourseArray[0].length; j++){ // or here
System.out.println("Enter the courseName");
nameCourseArray [i][j] =courseName.nextLine();
}
}
}
}
You only initialize the first dimension of the array :
String [][] nameCourseArray =new String [numberOfStudents.length][];
This means nameCourseArray[i]
is null, so nameCourseArray[0][0]
and nameCourseArray[i][j]
would throw a NullPointerException.
You must initialize the i'th sub-array with :
nameCourseArray[i] = new String[someLength];