Java - How to Find Students With Their Highest Marks Writing a Method in a Student Class

Printing out Highest Mark and Name of student

I created a class student:

public class Student {

private double mark;
private String name;

public Student()
{
mark = 0;
name = "";
}

public Student(int mark, String name)
{
this.mark = mark;
this.name = name;
}

public double getMark()
{
return mark;
}
public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public void setMark(double mark)
{
this.mark = mark;
}

}

then I edited your code in main

public static void main(String[] args) {
// TODO code application logic here

ArrayList<Student> studs = new ArrayList<Student>();
for(int i=0; i< 3; i++)
{
studs.add(new Student());
}

Scanner tomato = new Scanner(System.in);

double max;
int i;

for(i=0; i<3; i++) {
System.out.println("Enter name of student: ");
studs.get(i).setName(tomato.nextLine());
System.out.println("Enter marks: ");
studs.get(i).setMark(tomato.nextDouble());
tomato.nextLine();
}
int position = 0;
max = studs.get(0).getMark();
for(i = 0; i < 3; i++) {
if(max < studs.get(i).getMark()) {
max = studs.get(i).getMark();
position = i;
}
}
System.out.println("Highest marks:"+studs.get(position).getMark() + " student name " + studs.get(position).getName());
}

however, it is not the simplest choice

Edit: Simplier

   public static void main(String[] args) {
// TODO code application logic here


Scanner tomato = new Scanner(System.in);
double[] marks = new double[10];
String[] names = new String[10];
double max;
int i;

for(i=0; i<3; i++) {
System.out.println("Enter name of student: ");
names[i] = (tomato.nextLine());
System.out.println("Enter marks: ");
marks[i] = tomato.nextDouble();
tomato.nextLine();
}
int position = 0;
max = marks[i];
for(i = 0; i < 3; i++) {
if(max < marks[i]) {
max = marks[i];
position = i;
}
}
System.out.println("Highest marks:"+ marks[position] + " student name " + names[position]);
}

how can i find the total and the The highest marks in 2d array

Prerequisite

Before calculating highest mark and total marks for each student, you need two create two arrays to store that data. The size of the array will be the number of students.

int[] totalMarks = new int[studentsCount];
int[] highestMark = new int[studentsCount];


Logic

Once you have these, total and highest marks can be calculated in two different loops or one single loop.

For any student i,

highestMark[i] = max(marks[0][i], marks[1][i])
totalMarks[i] = marks[0][i] + marks[1][i]

To do the same process for all the students, use a simple for loop from i = 0 to studentCount.



Improvements

Your program can also be improved. Start giving meaningful name to your variables. Instead of NUMBER use studentCount. Even though Sc works okay, scanner is better. Another improvement is:

for(j=0;j<studentCount;j++) 
{
System.out.println ("For student " + (j+1) + ": ");

System.out.println("Enter the marks of the first semster: ");
marks [0][j]= scannner.nextInt();

System.out.println("Enter the marks of the second semseter: ");
marks [1][j]= scanner.nextInt();
}

You do not need for loop to input the mark for any student i for two semester.


I have not provided any code. I have given many hints which should help you solve the problem on your own. However, if you still face any problem. Do comment.

The method max(Comparator<? super List<Integer>>) in the type Stream<List<Integer>> is not applicable for the arguments (Comparator<Integer>)

For your current attempt you need to first get the max value for each student before comparing students max values to each other

studentData.stream().map(student -> Collections.max(student.getMarks()))
.max(Comparator.comparing(Integer::intValue)).get();

The problem with the above code is that it returns the highest mark and not the student so so it needs to be rewritten

studentData.stream().sorted((s1, s2) -> Collections.max(s1.getMarks()).compareTo(Collections.max(s2.getMarks())))
.findFirst().get();

The code above could be made easier to read if StudentData can give us the highest mark

public Integer highestMark() {
return Collections.max(this.getMarks());
}


studentData.stream().sorted((s1, s2) -> s1.highestMark().compareTo(s2.highestMark())).findFirst().get();

showing highest and lowest value of a series of objects in java

        initScore=score;

Please fix the above line in constructor.

Actually all the assignments are incorrect:

    public Student(String initName,String initID,int initScore){

initName=name;
initID=id;
initScore=score;
}

It should be changed to

    public Student(String initName, String initId, int initScore) {
name = initName;
id = initId;
score = initScore;
}

Even better

    public Student(String name, String id, int score) {
this.name = name;
this.id = id;
this.score = score;
}

Since score is not assigned in the initial construction, it is assigned a default value of 0 and hence impacts the min computation. (as its already at min assuming the scores are positive)

It works for max computation as the scores obtained will be greater than or equal to 0 and will eventually update the score directly(assuming only positive scores are allowed).

Get maximum of average subject marks using java 8 stream

Do not limit yourself to the idea of streams in Java 8 where you have to process a stream result directly into the next stream and so on... The efficiency might not be the best but consider to nest loops.

Start to think what you have: several marks for every Student. You want to find the average of these marks for every Student. You can reduce the problem to first think on how to get the average for one Student.

double average = student.getSubjectMarks().values().stream()
.mapToInt(Integer::valueOf).average().orElse(0.0);

Even though your examples show only integer numbers, averages can also be floating point numbers.

Then, you would have to loop through all students and execute the procedure above for every student.

Map<String, Double> studentAverages = new HashMap<>();

arr.forEach(student -> {
double average = student.getSubjectMarks().values().stream()
.mapToInt(Integer::valueOf).average().orElse(0.0);
studentAverages.put(student.getName(), average);
});

In the described implementation, the required averages are saved in the Map studentAverages which has the names of the students as a key and the average mark as a value.

You can then simply get the maximum integer from your list.

studentAverages.values().stream().mapToDouble(Double::doubleValue).max();

Some answers provide more sophisticated usages of streams. However, the code above is more readable. Furthermore, the data type Object is very general, difficult for further usage and error prone.

Java] How to calculate average score by subjects (using ArrayList)

From inside the Student class you can't get average scores by subjects since each student has a list of subjects. One possibility would be to define an accessor method for the list of subjects (i.e. Student#getSubjects() and use that outside of the student class to calculate the statistics by subject. You could also use a map to keep track of your totals, and counts, by subject.

For example:

Map<String, Integer> gradeTotalsBySubject = new HashMap<>();
Map<String, Integer> countsBySubject = new HashMap<>();
for (student : students) {
for (subject : student.getSubjects()) {
int currentGradeTotal = gradeTotalsBySubject.getOrDefault(subject.getName(), 0);
currentGradeTotal += subject.getScore();
gradeTotalsBySubject.put(subject.getName(), current);
int currentCount = countsBySubject.getOrDefault(subject.getName(), 0);
currentCount++;
countsBySubject.put(subject.getName(), currentCount);
}
}

This will give you the totals you need, and the numbers to divide by, grouped by subject. At that point you can iterate over the map entries in gradeTotalsBySubject and dividing each value by the count in the corresponding counts map you can get the averages.



Related Topics



Leave a reply



Submit