嘿伙计们,我正在尝试从文本文件中读取并将每个名称存储到链表节点中。 当我在文本文件中读取时,它会读取该行,这是一个名称。 我正在尝试将每个名称存储到链表节点中。 当我调用 insertBack 方法并将其打印出来时,它表明节点中没有任何内容。 谁能指出我正确的方向,将不胜感激?
这是文件在类中:
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
}
...
}