访问并将数据结构数据写入文件,但无法在try catch PrintWriter

时间:2017-12-16 23:53:15

标签: java eclipse data-structures static try-catch

我试图将双链接数据结构中的数据写入文件,但无法找到在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静态时,它说"非法修饰符,只允许最终#34;。所以我该怎么做?我对这里搜索类似主题的编程术语知之甚少,所以如果有人有这些主题的链接,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

  

但这需要我在try catch块中创建一个新的DoubleNode,

事实并非如此。这一行:

    dll.printlistF(dll.head); //THIS IS THE PLACE I CANT FIGURE IT OUT

将与代码中前面的这一行一样好用:

    dll.printlistF(dll.head); 

您的实际问题似乎是需要告诉printlistF打印数据的位置。为此,您需要:

  • PrintWriter方法声明中添加printlistF参数,该声明将是输出的目标
  • 在try块中打开目标(您已经完成了)并将其作为printlistF调用中的参数传递。
  

当我试图让dll静态时,它说"非法修饰符,只允许最后一次"。

  1. 没有必要这样做,在这种情况下它可能不会有帮助。
  2. dll变量是局部变量。局部变量不能声明为静态。
  3. 在OO程序中,静态变量通常是坏主意。如果您发现自己想要声明静态,那么应用程序设计通常会出现问题。
  4. 最后,如果你需要打印这样的列表,你的设计有问题:

    dll.printlistF(dll.head);
    

    在一个好的API设计中,head字段将是内部实现细节,它应该被隐藏;即声明为private。而不是将dll.head作为参数传递,print方法应该使用目标对象的head;即this.head