简体   繁体   中英

Java simple ragged Array query

I'm trying to write a Java program that will take as input:

  • The number of students
  • The number of courses taken by each student

It will then calculate the average for each student.

But I'm having trouble trying to read in the values. Please let me know what I could do to fix this problem.

My code is:

package q3;

import java.util.Scanner;
public class Q3 {

    public static void main(String[] args) {

        int [][] students;
        System.out.println("How many students? : ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        students = new int[num][];
        int [] numofcourses = new int[num];

        for(int i = 0;i<num;i++)
        {
            System.out.print("How many courses for student " + (i+1) + " : ");
            numofcourses[i] = in.nextInt();
            for(int j = 0;j<numofcourses[i];j++)
            {
                System.out.print("Enter grade " + (j+1) + " for student " + (i+1) + " : ");         
                students[i][j] = in.nextInt();
            }
        }
    }

}

Basically your problem is with this line

students = new int[num][];

and

students[i][j] = in.nextInt();

this one. because in java arrays you need to initialize the array before you use it. but in your first line you havent put a correct size of the array and which means the 2D array will not be defined correctly. so once you try to call it by using the second statement which I have mentioned here it is obviously null.

so your idea should be putting dynamic values as numberofcourses. But as in java you should define the size of the array before you use it. so in your case your idea should be to put another array into your base array(students) as the courses and that will be an int array and then you can use it it insert the courses.

so better go with

Object[][] data = new Object[numberOfStudents][1];

for loop

numOFSubjects = nextInt();
int[] no_of_sub = new int[numOFSubjects];

then

data[i][0] = no_of_sub ;

then to apply grades for loop for i and j

data[i][0][j] = nextInt();

done I think you got the idea. sorry for dummy code. I think its almost there.

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