gpt4 book ai didi

java - 将文本文件输入插入链接列表

转载 作者:行者123 更新时间:2023-12-02 06:34:50 25 4
gpt4 key购买 nike

嘿伙计们,我正在尝试从文本文件中读取并将每个名称存储到链接列表节点中。当我读入文本文件时,它会读取该行,这是一个名称。我试图将每个名称存储到链表节点中。当我调用insertBack方法并打印出来时,它显示节点中没有任何内容。有人能指出我正确的方向吗,我将不胜感激?

这是 fileIn 类:

import java.util.Scanner;

import java.io.*;

public class fileIn {
String fname;

public fileIn() {
getFileName();
readFileContents();
}

public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;

/* Read input from file and process. */
try {
in = new DataInputStream(new FileInputStream(fname));
LinkedList l = new LinkedList();

looping = true;
while(looping) {
/* Get a line of input from the file. */
if (null == (line = in.readLine())) {
looping = false;
/* Close and free up system resource. */
in.close();
}
else {
System.out.println("line = "+line);
j = 0;
len = line.length();
for(j=0;j<len;j++){
System.out.println("line["+j+"] = "+line.charAt(j));
}
}
l.insertBack(line);
} /* End while. */

} /* End try. */

catch(IOException e) {
System.out.println("Error " + e);
} /* End catch. */
}

public void getFileName()
{
Scanner in = new Scanner(System.in);

System.out.println("Enter file name please.");
fname = in.nextLine();
System.out.println("You entered "+fname);
}

}

这是 LinkedListNode 类:

public class LinkedListNode
{

private String data;
private LinkedListNode next;


public LinkedListNode(String data)
{
this.data = data;
this.next = null;
}

public String getData()
{
return data;
}

public LinkedListNode getNext()
{
return next;
}

public void setNext(LinkedListNode n)
{
next = n;
}
}

最后是具有 main 方法的 LinkedList 类:

import java.util.Scanner;

public class LinkedList {

public LinkedListNode head;

public static void main(String[] args) {

fileIn f = new fileIn();
LinkedList l = new LinkedList();
System.out.println(l.showList());
}

public LinkedList() {
this.head = null;
}

public void insertBack(String data){
if(head == null){
head = new LinkedListNode(data);
}else{
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = head;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(newNode);
}
}

public String showList(){
int i = 0;
String retStr = "List nodes:\n";
LinkedListNode current = head;
while(current != null){
i++;
retStr += "Node " + i + ": " + current.getData() + "\n";
current = current.getNext();

}

return retStr;
}
}

最佳答案

问题在于您在 fileIn 中创建了 LinkedList

但是你不导出它:

  fileIn f = new fileIn();
LinkedList l = new LinkedList();

你需要的是这样的:

  fileIn f = new fileIn();
LinkedList l = f.readFileContents(String filename, new LinkedList());

更改方法以使用您创建的LinkedList,然后填充它。所以 fileIn 类可能看起来像这样:

public class fileIn {
...
public void readFileContents(String fileName, LinkedList) {
// fill linked list
}
...
}

关于java - 将文本文件输入插入链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19761432/

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