[英]Returning object with max value inside of a linked List java
I'm working on method bestStudent(). 我正在研究bestStudent()方法。 I return the student with the highest GPA.
我让GPA最高的学生返回。 I keep getting an error Student cannot be converted to LinkedList.node.
我不断收到错误消息,无法将Student转换为LinkedList.node。 I'm trying to use a while loop to return the object Student with the highest gpa.
我正在尝试使用while循环返回gpa最高的对象Student。
public class LinkedListStud
{
private Node list;
public LinkedListStud()
{
list = null;
}
public boolean isEmpty()
{
return (list == null);
}
public void addFront(Student s)
{
Node newNode = new Node(s);
newNode.next = list;
list = newNode;
}
public void addTail(Student s)
{
Node newNode = new Node(s);
Node current;
if (isEmpty())
list = newNode;
else
{
current = list;
while(current.next !=null)
current = current.next;
current.next = newNode;
}
}
public Student bestStudent()
{
Node current = list;
while (current.next != null)
if (current.data.getGPA() > current.next.data.getGPA())
return current = current.data;
}
public void printLinkedList()
{
Node l = list;
while (list != null)
l.toString();
System.out.println("next Link: " + l.next);
l = l.next;
System.out.println();
}
private class Node
{
public Student data;
public Node next;
public Node(Student s)
{
data = s;
next = null;
}
}
}
public class Student implements Comparable<Student>
{
public String lastName;
public double gpa;
public int age;
public Student(String lastName, double gpa, int age)
{
this.lastName = lastName;
this.gpa = gpa;
this.age = age;
}
public int compareTo(Student s)
{
return (this.gpa < s.gpa) ? -1 : (this.gpa > s.gpa) ? 1: 0;
}
public String toString()
{
return "Student: \t" + lastName + "GPA: \t" + gpa+ "Age: \t" + age;
}
public double getGPA()
{
return gpa;
}
}
You should do something along the lines of below in order to make that method work. 您应该按照以下步骤进行操作,以使该方法起作用。
public Student bestStudent() {
Node current = list;
Student bestStudent = null;
while(current.next != null) {
if(bestStudent == null || (current.next != null && (current.data.getGPA() > current.next.data.getGPA()))) {
bestStudent = current.data;
}
}
return bestStudent;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.