我正在学习 Java,并被要求提供可用于根据输入的学生姓名和分数收集统计数据的方法。我已经弄清楚如何计算最高分,但我需要做的是返回获得最高分的学生的姓名,我该怎么做?我想我可以尝试返回最高整数之前的字符串,但我不确定如何做到这一点。
编辑:澄清一下,目前,当输入数据后在控制台中输入 END 时,会返回最高分 - 我需要返回最好学生的分数。
import java.util.*;
public class Course {
private ArrayList<Student> people = new ArrayList<Student>();
private int passing = 0;
private int failing = 0;
private int top = Integer.MIN_VALUE;
private int sum = 0;
public void add( Student student ) {
people.add( student );
if(student.getMark() >= 40){
passing++;
}
else {
failing++;
}
sum += student.getMark();
if(student.getMark() > top) {
top = student.getMark();
}
}
public int pass() {
return passing;
}
public int fail() {
return failing;
}
public int top() {
return top;
}
public double average() {
return sum / people.size();
}
}
感谢您的帮助。
更新:BinaryJudy,我按照你说的做了,但我收到顶级名称的“NoSuchMethod”错误,这就是我将代码更改为:
import java.util.*;
public class Course {
private ArrayList<Student> people = new ArrayList<Student>();
private int passing = 0;
private int failing = 0;
private int top = Integer.MIN_VALUE;
private int sum = 0;
private String topName;
public void add( Student student ) {
people.add( student );
if(student.getMark() >= 40){
passing++;
}
else {
failing++;
}
sum += student.getMark();
if(student.getMark() > top) {
top = student.getMark();
}
if(student.getMark() > top) {
top = student.getMark();
topName = student.getName();
}
}
public int pass() {
return passing;
}
public int fail() {
return failing;
}
public String top() {
return topName;
}
public double average() {
return sum / people.size();
}
}
知道为什么吗? :)
您已经找到了得分最高的学生。找到顶部标记后,用学生的姓名更新顶部名称。找到顶部标记也会找到名称。
String topName;
if(student.getMark() > top) {
top = student.getMark();
topName = student.getName();
}
我是一名优秀的程序员,十分优秀!