Kero Kero Kero Kero - 1 month ago 5
Java Question

2D array data null?

I have created a program to accept input from user and will store in 2d array. Example situation, the user enter an input no of semester = 2; then the no of course also = 2;. My loop is working correctly, but the data is not store well.

The output :
null
null
null
input4

It should like this :
input1
input2
input3
input4

Here my code :

BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));

try {

System.out.print("Enter no of semester : ");
data = inData.readLine();
noSem = Integer.parseInt(data);

// Semester loop
for(int i = 0; i < noSem; i++) {

System.out.println("\n\tSemester" + (i + 1));
System.out.print("Enter number of course : ");
data = inData.readLine();
noCourse = Integer.parseInt(data);

// course details loop
for(int u = 0; u < noCourse; u++) {

System.out.println("Enter Course Code : ");
System.out.print("Enter Course Name : ");
sbjName = new String[noSem][noCourse];
sbjName[i][u] = inData.readLine();

System.out.println("Enter Credit Hour : ");
System.out.println("Enter Marks : ");
System.out.println("\n");

}
}

for(int x = 0; x < noSem; x++) {
for(int y = 0; y < noCourse; y++) {
System.out.println(sbjName[x][y]);
}
}
}

Answer
BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));

try {
    System.out.print("Enter no of semester : ");

    int noSem = Integer.parseInt(inData.readLine());
    String[][] sbjName = new String[noSem][];

    // Semester loop
    for (int i = 0; i < noSem; i++) {
        System.out.println("\n\tSemester" + (i + 1));
        System.out.print("Enter number of course : ");

        int noCourse = Integer.parseInt(inData.readLine());
        sbjName[i] = new String[noCourse];

        // course details loop
        for (int u = 0; u < noCourse; u++) {
            System.out.println("Enter Course Code : ");
            System.out.print("Enter Course Name : ");
            sbjName[i][u] = inData.readLine();

            System.out.println("Enter Credit Hour : ");
            System.out.println("Enter Marks : ");
            System.out.println("\n");
        }
    }

    for (int x = 0; x < sbjName.length; x++) {
        for (int y = 0; y < sbjName[x].length; y++) {
            System.out.println(sbjName[x][y]);
        }
    }
}