我试图将数据从双链接数据结构写入文件,但无法找到在Printwriter try catch块中打印它的方法:
public static void main(String[] args) {
/* Start with the empty list */
LinkedList lk = new LinkedList();
Order x = new Order("1", "x", 1);
Order y = new Order("2", "y", 1);
DoubleNode dll = new DoubleNode();
File f = new File("/Users/Dell/Documents/product.txt");
Product a = new Product("1", "a", 1, 1, 1.);
Product b = new Product("2", "b", 2, 2, 2.);
Product c = new Product("3", "c", 3, 3, 3.);
Product d = new Product("4", "d", 4, 4, 4.);
Product e = new Product("5", "e", 5, 5, 5.);
dll.append(b);
dll.push(d);
dll.push(a);
dll.append(c);
dll.InsertAfter(dll.head.next, e);
System.out.println("Created DLL is: ");
dll.printlistF(dll.head);
String filePath;
try {
f.createNewFile();
filePath = f.getCanonicalPath();
}
catch(IOException io) {
io.printStackTrace();
}
if (f.exists()) {
System.out.println("File exist.");
System.out.println("File is readable: " + f.canRead());
System.out.println("File is writeable: " + f.canWrite());
System.out.println("File is location: " + f.getName());
}
try {
PrintWriter output = new PrintWriter(f);
dll.printlistF(dll.head); //THIS IS THE PLACE I CANT FIGURE IT OUT
output.close();
} catch (IOException e2) {
// TODO: handle exception
System.out.println("ERROR"+e2);
}
}
但这需要我在try catch块中创建一个新的DoubleNode,当我试图使dll静态时,它说“非法修饰符,只允许最终”。所以我该怎么做?我不太了解编程术语来搜索这里的类似主题,所以如果有人有链接到它们,将不胜感激。
但这需要我在try catch块中创建一个新的DoubleNode,
事实并非如此。这一行:
dll.printlistF(dll.head); //THIS IS THE PLACE I CANT FIGURE IT OUT
将从代码中的前一行开始工作:
dll.printlistF(dll.head);
你的实际问题似乎是你需要告诉printlistF
在哪里打印数据。为此,您需要:
PrintWriter
参数添加到printlistF
方法声明中,该声明将是输出的目标。printlistF
调用中的参数传递。当我试图使dll静态时,它说“非法修饰符,只允许最终”。
dll
变量是局部变量。局部变量不能声明为静态。最后,如果您需要打印如下列表,您的设计会出现问题:
dll.printlistF(dll.head);
在一个好的API设计中,head
字段将是一个内部实现细节,它应该被隐藏;即宣布为private
。而不是将dll.head
作为参数传递,print方法应该使用目标对象的head
;即this.head
。