0

I'm trying to create an array to collect students, and a grades array for each student. My int count will increment with a while loop or something. The problem is my Students array gets an error. Is there an alternative method?

static int count = 0;

static int[] Grades = new int[count];

static String[] Students =  new String[Grades[count];
3
  • 3
    Consider writing a Student class and then use a Student[] or a List<Student>. Commented Feb 17, 2013 at 17:18
  • 1
    Maybe consider a Map<Student, Grade> Commented Feb 17, 2013 at 17:19
  • 1
    With count set to 0, you'll always have a zero-length array, which you can never index into. Commented Feb 17, 2013 at 17:20

4 Answers 4

1

You can create a Student class which contains name, age...etc and an Array/List of grades :

class Student {
  String name;
  String age;
  //...
  List<Integer> grades;

  //Getters & Setters of course
}

You can add a method that grab a map of {name:grades}

Sign up to request clarification or add additional context in comments.

Comments

1

This design will create lot many problems for you in future. If you really want to stick with array., Do consider two dimensional arrays.

A better and clean design will be to use maps as follows.

map<Student, List<Grades>>  studentGrades= new Hashmap <Student, List<Grades>>() ;

1 Comment

If you can use 3rd party libraries then there is the Guava multimap
0

How about:

Map<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();

To add:

String student = "Bobby";
int mark = 85;
if (map.containsKey(student))
  map.get(student).add(mark);
else
{
  ArrayList<Integer> arr = new ArrayList<Integer>();
  arr.add(mark);
  map.put(student, arr);
}

To display:

System.out.println(map);

or:

for (Entry<String, ArrayList<Integer>> entry: map.entrySet())
  System.out.println("Marks of " + entry.getKey() + " = " + entry.getValue());

To extend functionality to allow students to have more properties:

class Student
{
  ArrayList<Integer> marks;
  // ...
}

Declaration:

Map<String, Student> students = new HashMap<String, Student>();

Comments

0

You can have a two-dimentional array. something like an array of arrays, that each item holds an entire array:

int[][] students = new int[num_of_students][]

Then you can dinamically change the length of each array for each student:

for (int i = 0; i < num_of_stuent; i++)
     students[i] = new int[i + 1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.