繁体   English   中英

java-从链接列表中找到最大值

[英]java - find the max value from a linked list

免责声明:我是一个非常早期的学生,正在努力学习Java。 请告诉我是否遗漏任何重要信息。

我正在编写一个程序,提示用户对链接列表进行各种操作(添加,删除,更改值等),但不是存储字符串或某些原始数据类型,而是存储了Student类型的对象(基本上包含一个用于表示学生姓名的字符串和一个用于其测试分数的整数),并且由于我无法找到最高的学生,因此在如何找到最大的测试分数上受了限制。

任何帮助,将不胜感激。

好了,您可以有两个变量,一个是currentScore,另一个是newScore。 然后遍历每个学生对象,获取测试值,然后进行比较。 如果新分数较低,则保持最新。 如果新分数更高,请用新分数替换当前分数,并继续遍历。 遍历列表时,您的得分最高

您可以按照描述的其他答案遍历列表,也可以使用Collections.max方法。 要使用此方法,您的Student类应实现可扩展接口。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM