gpt4 book ai didi

java - 链表从文件读取、排序和离一错误

转载 作者:行者123 更新时间:2023-12-01 16:56:53 25 4
gpt4 key购买 nike

我必须创建一个链接列表来读取字符串和关联的 int 文件,并在读取时按 int 进行排序。到目前为止,我已经获得了一个将元素添加到列表中的方法,以及一个基本的读取方法(但由于某种原因缺少文件中的最后一个元素),但是每次我尝试向读取方法添加条件时,它都会返回一个空列表。

我的添加方法:

public void addFirst(String name, int rank)
{
Ship newShip = new Ship(name, rank);

if (isEmpty())
{
newShip.next = null;
newShip.prev = null;
last = newShip;
first = newShip;
}
else
{
first.next = newShip;
newShip.prev = first;
first = newShip;
}
}

以及我的工作(但相差一)读取方法:

public void readFile(String filename) throws IOException
{
try
{
File inFile = new File(filename); //inst. file import
Scanner read = new Scanner(inFile); //inst. scanner object

while (read.hasNext()) //reads until end of text
{
String name = read.next(); //scanner reads next string, assigns to name
int rank = read.nextInt(); //reads next int, assigns to rank
addFirst(name, rank); //enqueues ship name and rank into list
}
read.close(); //ends read when empty
}

catch(IOException exc)
{
System.out.println("Error: file not found");
}

}

每次我在 read 方法中的 while() 中添加一个条件时,如下所示(数据文件中有一个“0”):

    while (read.hasNext())                      //reads until end of text
{
String name = read.next(); //scanner reads next string, assigns to name
int rank = read.nextInt(); //reads next int, assigns to rank
if (rank == 0)
{
addFirst(name, rank); //enqueues ship name and rank into list
}
}

Tt 似乎根本没有读过这个列表。如果我无法弄清楚 add 方法失​​败的原因,我就无法开始在插入算法中添加条件。

编辑:添加示例数据集。我只需要弄清楚我在概念上搞砸了。

船舶1 0 船2 10 船3 27 船4 2 船5 7 ....

编辑2:

好吧,暂时放弃使用链表来计算插入,而只是创建一个基于哨兵的插入 read() 方法。感谢您的帮助。

最佳答案

只是在这里问,因为它太大了,无法发表评论:

假设addFirst方法用于添加到链表的头部,并且Ships确实具有属性nextprev,你不想吗:

if(!isEmpty){

first.prev = newShip;
newShip.next = first;
first = newShip;

}

或者如果你想在链接列表的尾部添加,你不想要:

if(!isEmpty){

last.next = newShip;
newShip.prev = last;

// take out first = newShip

}

无论哪种方式,您所拥有的似乎都可能不正确。如我错了请纠正我。

关于java - 链表从文件读取、排序和离一错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31502544/

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