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

问题描述 投票:-1回答:1

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

java eclipse data-structures static try-catch
1个回答
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程序中通常是一个坏主意。如果您发现自己想要声明静态,那么您的应用程序设计通常会出现问题。

最后,如果您需要打印如下列表,您的设计会出现问题:

dll.printlistF(dll.head);

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

© www.soinside.com 2019 - 2024. All rights reserved.