声明:我是一名非常早期的学生,并且正在努力学习java。请告诉我,如果我遗漏了任何重要的信息。我正在写一个程序,提示用户做一个链接列表(添加,删除,更改值等)的各种操作,而不是存储一个字符串或一些原始数据类型我正在存储的类型学生的对象(其中基本上包含一个字符串作为学生的名字和他们的测试分数的整数),并坚持如何找到最大的考试分数,因为我不能找到最高的学生。java - 从链接列表中找到最大值
任何帮助,将不胜感激。
声明:我是一名非常早期的学生,并且正在努力学习java。请告诉我,如果我遗漏了任何重要的信息。我正在写一个程序,提示用户做一个链接列表(添加,删除,更改值等)的各种操作,而不是存储一个字符串或一些原始数据类型我正在存储的类型学生的对象(其中基本上包含一个字符串作为学生的名字和他们的测试分数的整数),并坚持如何找到最大的考试分数,因为我不能找到最高的学生。java - 从链接列表中找到最大值
任何帮助,将不胜感激。
那么你可以有两个变量,一个作为currentScore,另一个作为newScore。然后遍历每个学生对象,获取测试值,然后进行比较。如果新分数较低,则保持最新。如果新分数较高,请用新分数替换当前分数,并继续遍历。当遍历列表时,得到的分数最高
您可以按照其他描述进行迭代,也可以使用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)
你会得到分数最高的学生。
我写了一个简单的程序来匹配你的情况。
主类:
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: 10