免责声明:我是一个非常早的学生,正在努力学习java。如果我遗漏了什么重要信息,请告诉我。
我正在编写一个程序,提示用户对链表执行各种操作(添加、删除、更改值等)。但是,我没有存储字符串或一些原始数据类型,而是存储了类型为Student的对象(它基本上包含一个表示学生姓名的字符串和一个表示他们考试分数的整数),并且被困在如何找到最高考试分数的问题上,因为我不能只找到最高的Student。
任何帮助都将不胜感激。
发布于 2015-09-25 08:05:00
你可以有两个变量,一个作为currentScore,另一个作为newScore。然后遍历每个学生对象,获取测试值,然后进行比较。如果新的分数较低,则保持最新。如果新的分数更高,用新的分数替换当前的分数,并继续遍历。当你遍历列表时,你会得到最高分
发布于 2015-09-25 10:34:05
您可以按照描述的其他答案遍历列表,也可以使用Collections.max方法。要使用此方法,您的学生类应该实现comperable接口。
public class Student implements Comparable<Student>并且需要将compareTo方法添加到类中:
@Override
public int compareTo(Student student)
{
if (this.score > student.score)
{
return 1;
}
if (this.score < student.score)
{
return -1;
}
else
{
return 0;
}
}现在,当您编写Collections.max(list)时,您将获得分数最高的学生。
发布于 2015-09-25 11:19:30
我写了一个简单的程序来匹配你的情况。
主类:
import java.util.*;
import java.lang.Math;
public class FindHighestScore
{
public static void main(String[] args)
{
LinkedList<Student> studentLinkedlist = new LinkedList<Student>();
studentLinkedlist.add(new Student("John",1)); // Adding 5 students for testing
studentLinkedlist.add(new Student("Jason",5));
studentLinkedlist.add(new Student("Myles",6));
studentLinkedlist.add(new Student("Peter",10)); // Peter has the highest score
studentLinkedlist.add(new Student("Kate",4));
int temp = 0; // To store the store temporary for compare purpose
int position = 0; // To store the position of the highest score student
for(int i = 0; i < studentLinkedlist.size(); i ++){
if(studentLinkedlist.get(i).getScore() > temp){
temp = studentLinkedlist.get(i).getScore();
position = i;
}
}
System.out.println("Highest score is: " + studentLinkedlist.get(position).getName());
System.out.println("Score: " + studentLinkedlist.get(position).getScore());
}
}学生构造函数类:
public class Student
{
String name;
int score;
Student(){
}
Student(String name, int score){
this.name = name;
this.score = score;
}
String getName(){
return this.name;
}
int getScore(){
return this.score;
}
}上述程序产生如下结果:
Highest score is: Peter
Score: 10https://stackoverflow.com/questions/32772767
复制相似问题