【发布时间】:2013-11-14 16:48:31
【问题描述】:
大家好,我正在尝试从文本文件中读取并将每个名称存储到链表节点中。当我读入文本文件时,它会读取该行,这是一个名称。我正在尝试将每个名称存储到一个链表节点中。当我调用 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;
}
}
【问题讨论】:
-
您是否在控制台中看到从调试语句中打印出的读取文本?
-
我会推荐
BufferedReader和InputStreamReader而不是DataInputStream。DataInputStream.readLine已弃用。 -
在控制台中,我可以看到它在哪里显示 line=Shawn(或任何其他名称)广告,然后显示每个字母都存储在 line[j] 上的数组中。当它到达我的 showList 方法时,它只显示 List Nodes: 之后没有其他内容。
-
啊,很高兴知道,我会在试图找出问题所在的同时尝试改变它。
标签: java file-io linked-list