There is a program to calculate the average of marks of students. When the program is running, it will be asked the student's name at first. Then, the student will be able to enter the subject name and then the marks for that subject. When all marks have been entered, the average will be displayed.
I need to store String (for subjects) and Integer (for marks) values in a single cell (cell means a single box of the data structure) at one time. Is there a data structure to do so or if isn't, what is the best way to do that ?
CodePudding user response:
You could use a hashmap where student names are the key, and the value is another hashmap. For each student there use another hashmap where the subject is the key, and the value is an array storing the marks.
CodePudding user response:
Yes, you can declare the array as an Object[] array.
You can create a 2D Object[][] array, where each cell corresponds to one student. The following code shows how to create and iterate over it.
Object[][] array = {{"Mark1", 1, "Mark2", 4}, {"Mark1", 1, "Mark2", 4}};
for(Object[] i : array) {
for(Object j : i) {
System.out.print(j " ");
}
System.out.println("");
}
However, you may prefer using a HashMap.
import java.util.HashMap;
HashMap<String, HashMap<String, Integer>> marks = new HashMap<>();
HashMap<String, Integer> marks1 = new HashMap<>();
marks1.put("course1", 53);
marks.put("student1", marks1);
System.out.println(marks.get("student1").get("course1"));
CodePudding user response:
Record
Is there a data structure
In Java, you define your own data structures by writing a class.
Java 16 and later makes this easier with the new records feature. A record is a brief way of writing a class whose main purpose is to communicate data transparently and immutably. The compiler implicitly creates constructor, getters, equals
& hashCode
, and toString
.
record SubjectMark ( String subject , int mark ) {}
And define student.
record Student ( String name , Set< SubjectMark > marks ) {}
Example usage.
List< Student > students = new ArrayList <> () ;
…
students.add(
new Student(
"Alice" ,
Set.of(
new SubjectMark ( "French" , 3 ) ,
new SubjectMark ( "Math" , 4 ) ,
new SubjectMark ( "History" , 2 )
)
)
);
Note that you can declare a record locally within a method, as well as nested, or in its own .java
file.
To calculate an average mark, loop the SubjectMark
objects.
record Student ( String name , Set< SubjectMark > marks )
{
double average()
{
int sum = 0 ;
for( SubjectMark subjectMark : this.marks )
{
sum = sum subjectMark.mark ;
}
return ( sum / this.marks.size() ) ;
}
}
Streams would make this code simpler, but that is more advanced Java.