Java - 使用数组查找/打印最小值/最大值? [英] Java - Finding/Printing Min/Max with Array?

查看:59
本文介绍了Java - 使用数组查找/打印最小值/最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: 我将如何从数组中找到最小值/最大值以及语法是什么样的?

((开始研究它可能是什么样子(在这篇文章的底部),但我没有得到正确的语法))

想在我的主类中创建一个方法,从一组学生中找出成绩最好和最差的学生(并打印),但不确定数组的语法如何.

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

}    
}

推荐答案

以下内容如何:

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

或更短的使用 java 8 lambdas:

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
}

这篇关于Java - 使用数组查找/打印最小值/最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆