【发布时间】:2020-02-18 00:32:50
【问题描述】:
我正在尝试创建一个 LinkedList 类,该类能够从内容中添加为数据文件。我被抛出一个 NullPointerException,我不完全确定为什么。有没有更好的方法来解决这个问题而不使用 Collections.sort?
public class LinkedList {
// Properties
Node head;
int count;
// Constructors
public LinkedList() {
head = null;
count = 0;
}
public LinkedList(Node newHead) {
head = newHead;
count += 1;
}
// Methods
// add
public void add(String newData) {
Node temp = new Node(newData);
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(temp);
count++;
}
//================================================================================================
public static void main(String[] args) throws IOException {
// Access the contents of a file
File file = new File("C:\\Users\\Marlene\\Workspace\\LinkedDict\\src\\com\\company\\unsorteddict.txt");
Scanner scan = new Scanner(file);
String fileContents = "";
LinkedList linkedList = new LinkedList();
com.company.LinkedList linkedList = new com.company.LinkedList();
while (scan.hasNextLine()) {
linkedList.add(fileContents);
}
FileWriter writer = new FileWriter(
"C:\\Users\\Marlene\\Workspace\\LinkedDict\\src\\com\\company\\sorteddict.txt");
writer.write(fileContents);
writer.close();
}
}
【问题讨论】:
-
欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。特别是,包括完整的错误消息(回溯)和您对关键值的跟踪。
标签: java sorting linked-list nullpointerexception