2

Question: How would I go about finding min/max from array and what would the syntax look like?

((Edit: Started working on what it might look like (at the bottom of this post), but I'm not getting the syntax right))

Would like to create a method in my main class to find the students with the best and worst grades (and print) from an array of students, not sure about how the syntax would look with an array.

Main.java

import java.util.*;
import java.io.*;

public class Main
{
private static int i=0;

public static void main (String[] args) throws IOException
{                        
    Student[] arrStudents = new Student[7];

    Scanner fileInput = new Scanner(new File("students.txt")); 

    while (fileInput.hasNext())
    {             
        String firstName = fileInput.next();
        String lastName = fileInput.next();
        int grade = fileInput.nextInt();

        arrStudents[i] = new Student(firstName, lastName, grade);
        i++;
    }  

    getExcellentStudents(arrStudents);
    getOKStudents(arrStudents);
    getFailStudents(arrStudents);
    System.out.println(); 
    System.out.println("Total Number of Students: " + arrStudents.length);
}

public static void getExcellentStudents(Student[] arrStudents) throws IOException {               
    System.out.println("Excellent Students: ");
    for(int i = 0; i < arrStudents.length; i++) {
       int grade = arrStudents[i].getGrade();

        if (grade > 89) {                    
            System.out.println(arrStudents[i]);
       }
    }
    System.out.println();
}


public static void getOKStudents(Student[] arrStudents) throws IOException {               
    System.out.println("OK Students: ");
    for(int i = 0; i < arrStudents.length; i++) {
       int grade = arrStudents[i].getGrade();

        if (grade > 60 && grade < 90) {
            System.out.println(arrStudents[i]);
       }
    }
    System.out.println();
}


public static void getFailStudents(Student[] arrStudents) throws IOException {     
    System.out.println("Failure Students: ");
    for(int i = 0; i < arrStudents.length; i++) {
       int grade = arrStudents[i].getGrade();

        if (grade < 61) {
            System.out.println(arrStudents[i]);
       }
    }
    System.out.println();
}

Student.java

public class Student {
private String firstName, lastName;
private int grade;

public Student (String firstName, String lastName, int grade)
{
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
}

public String toString()
{
    return firstName + " " + lastName + " " + grade;
}

public int getGrade()
{
    return grade;
}
}

students.txt

John Smith 90
Barack Obama 95
Al Clark 80
Sue Taylor 55
Ann Miller 75
George Bush 58
John Miller 65

Here's how the output should look (so I'm missing the last two lines right now):

Excellent Students: 
John Smith 90
Barack Obama 95

OK Students: 
Al Clark 80
Ann Miller 75
John Miller 65

Failure Students: 
Sue Taylor 55
George Bush 58


Total Number of Students: 7
Student With Highest Grade: Barack Obama 95
Student With Lowest Grade: Sue Taylor 55

Easier to edit here than to post in the comments. I updated the post to make it a little more clear about what I'm asking.

Here's what I had so far for finding the max, but I'm still confused on what goes where exactly.

public void outputMaxMin(Student[] arrStudents) throws IOException {       
Student bestStudent;
Student worstStudent;
student = new Student();

for (int i = 0; i < arrStudents.length; i++) {
  int grade = arrStudents[i].getGrade();
  if (bestStudent == null && worstStudent == null) {
    bestStudent = student;
    worstStudent = student;
    continue; 
  } 

  if (grade > bestStudent.grade){
    bestStudent = student;
  }
  if (grade < worstStudent.grade){
    worstStudent = student;
  }

}    
}
4
  • 5
    Use one loop to go through all the students, keeping max and min values associated with the Student's grade. And at the end print them. Commented May 8, 2014 at 19:29
  • 4
    I couldn't find the question in your question... Commented May 8, 2014 at 19:29
  • Tried to update the original post to make it more clear, and I was originally working on a loop, but the syntax is kind of, well, not good. I also posted it in my original post (right at the end). Commented May 8, 2014 at 19:38
  • @user3594736 You're almost done. Just move Student student = arrStudents[i]; to be the first instruction in the for loop. Commented May 8, 2014 at 19:44

3 Answers 3

1

how about the following:

// assume students.length > 0
static void printMinMax(Student[] students) {
  Student min = students[0];
  Student max = students[0];

  for (Student student: students) {
    if (student.getGrade() > max.getGrade())
      max = student;
    if (student.getGrade() < min.getGrade())
      min = student;
  }

  System.out.println("Best student: " + max);
  System.out.println("Worst student: "+ min);
}

On another note, you should really consider using Collections instead of plain arrays. Especially since you do not really know the number of students beforehand.

Above code could be rewritten like this:

static void printMinMax(List<Student> students) {
  Comparator<Student> comparator = new Comparator<>() {
    @Override public int compare(Student s1, Student s2) {
      return s1.getGrade() - s2.getGrade();
    }
  };
  Student max = Collections.max(students, comparator);
  Student min = Collections.min(students, comparator);

  // print stuff
}

or shorter using java 8 lambdas:

static void printMinMax(List<Student> students) {
  Comparator<Student> comparator = (s1, s2) -> s1.getGrade() - s2.getGrade();

  Student max = Collections.max(students, comparator);
  Student min = Collections.min(students, comparator);

  // print stuff
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Worked perfectly! (Narble's code helped me out too, but yours is cleaner - sorry Narble :( )
please also consider using Collections (see edit) - especially while learning the language these should be prefered to raw arrays IMHO.
Definitely would, but knowing my professor he wouldn't like it. I did this program before using a new StudentHandler class that used ListArrays, and I got a 0/10 on that (gave me the opportunity to resubmit), just trying to clean everything up by doing exactly what he wants this time. All I need to do now is find out how to sort the Excellent, OK, and Failure students with a bubble sort to get +2 points on this.
1

To get the highest and lowest grade simply loop through all items in the array while keeping 2 variables for highest and lowest.

int highest = 0;
int lowest = 100;
Student high = arrStudents[0];
Student low = arrStudents[0];

for (int index = 0; index < arrStudents.length; index++)
{
    if (arrStudents[index].getGrade() > highest)
    {
         highest = arrStudents[index].getGrade();
         high = arrStudents[index];
    }
    else if (arrStudents[index].getGrade() < lowest)
    {
         lowest = arrStudents[index].getGrade();
         low = arrStudents[index];
    }
}
System.out.println("Student with the highest grade: " + high);
System.out.println("Student with the lowest grade: " + low);

Then print them out the way you like. Hope this helps.

5 Comments

Almost, but it still only just gives me the grade. Just double checked, and ya, still only the grades. Not sure I can use Student high; and Student low;
The Student high and low is what you will print from with your toString. I updated the code to reflect the printing.
Sorry, still a newbie, I can't just do: System.out.print(high);? Says high hasn't been initialized.
If need be just initialize both high and low to arrStudents[0] to shut the compiler up. It is basically just telling you that it is possible that high and low will not have been initialized to a stduent which means there is no toString to print. I updated my code.
Yup, that worked! Thanks! I actually still have to write something up to find the average now, but that should be easier.
0

You would need to loop thought the array and keep a value for max and min

Student[] arrStudents = new Student[7];
Student max=arrStudents[0];
Student min=arrstudents[1];
for (int i=0; i < arrStudents.length(); i++){
   if arrStudents[i].getGrade() >max.getGrade(){
      max = arrStudents[i];
   }
   else if arrStudents[i].getGrade() <min.getGrade(){
      min =arrStudents[i];
   }
}

2 Comments

Already had the arrStudents in my method, so: public static void outputMaxMin(Student[] arrStudents) throws IOException { - also says it can't find variable max?
you need to initialize min and max as Student type. you might also need to adapt the code to make it fit yours a little better.

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.