gpt4 book ai didi

java - 如何访问存储在单链表节点中的对象的特定变量(迭代)

转载 作者:行者123 更新时间:2023-12-02 12:00:24 29 4
gpt4 key购买 nike

这是一个非常具体的问题,我似乎找不到任何特别有帮助的内容。我有一个单链表(不是一个实现的链表,这是我能找到的全部),其中节点存储一个 Student 对象。每个 Student 对象都有变量,尽管我在访问每个变量时遇到问题。

我认为它应该类似于迭代对象数组的方式。但是它使用 for 循环。要遍历链接列表,您必须使用节点及其下一个数据值。

我不完全确定如何结合这两个想法。我觉得这要么是我没有得到的愚蠢简单的东西,要么是我应该采取一种完全不同的方法。

import java.util.scanner;

public class StudentNode extends Student
{
private Student data;
private StudentNode next;


class SinglyLinkedList
{

private StudentNode first;

//constructor
public SinglyLinkedList()
{
first=null;
}


public addToList(Student newData)
{
StudentNode newNode= new StudentNode();
newNode.data=newData;
newNode.next=first; //refs to the element first is currently pointing to
first=newNode;//first now refs to added element
}

public courseMark(Student data)
{
double cm=courseMark(StudentNode.data);
return "Student number : "+stuNum +"Course Mark: "+cm;

}



public double classAverage(Student data)
{
//traverses linked list, not enirely sure about how to access the course mark
double classAvg=0;
double sum = 0;
int i=0;
StudentNode current = first;
StudentNode previous = null;
while (current != null)
{
i++;
StudentNode current= Student.courseMark();
sum += current.data;//not sure bout course mark access
previous = current;
current = current.next;
}
return classAvg=sum/i;
}

这是数据组件使用的 Student 类。不确定是否需要回答。

public class Student
{
private String name;
private String stuNum;
private int firstTest;
private int secondTest;
private int thirdTest;

public Student(String n,String sN,int fT,int sT,int tT)
{
name=n;
stuName=sN;
firstTest=fT;
secondTest=sT;
thirsTest=tT;
}

//setters
public void setName(String n)
{
name=n;
}

public void setStuNum(String sN)
{
stuNum=sN;
}

public void setFirstTest(int fT)
{
firstTest=fT;
}

public void setSecondTest(int sT)
{
secondTest=sT;
}

public void setThirdTest(int tT)
{
thirdTest=tT;
}

//getters

public String getName()
{
return name;
}

public String getStuNum()
{
return stuNum;
}

public int getFirstTest()
{
return firstTest;
}

public int getSecondTest()
{
return secondTest;
}

public int getThirdTest()
{
return thirdTest;
}

//course mark computer

public double courseMark()
{
double crseMark=(firstTest*0.25)+(secondTest*0.25)+(thirdTest*0.50);
return crseMark;
}

}

最佳答案

必须从节点遍历到学生数据才能获取 courseMark。

while (当前!​​= null) {
...
双 courseMark = current.data.courseMark();
...
}

关于java - 如何访问存储在单链表节点中的对象的特定变量(迭代),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47298442/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com