Java - Finding/Printing Min/Max with Array?

2019-01-20 15:03发布

问题:

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;
  }

}    
}

回答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
}


回答2:

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.



回答3:

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];
   }
}