Java,在文件中写入数据并在多行上分割

问题描述:

我有一个双链表,在该表中我必须生成100个随机值。我已经做到了。然后,我需要将双链表的值存储到文本文件中。我也是这样做的。 最后,我必须格式化我的文件,有就行,例如5个值:Java,在文件中写入数据并在多行上分割

TIP:我会写这些线为随机值,不事秩序,我用冒泡排序他们,我后逆转他们,但我需要的是知道如何把这些值是这样的:

1 14 23 4 55 
6 39 91 1 4 

etc. 

我也试着重写的toString和我说有“为”和“如果”,但结果还是失败。这里是我的代码:

DLL ran = new DLL(); //this is my class named DLL 
    for(int i=0; i<100; i++) 
    { 
     Integer n = new Integer((int) (Math.random()*100)); 
     ran.startValue(n);  //this is my add function, to add elements in list 
     System.out.print(n+" "); 
    } 

    BufferedWriter out = new BufferedWriter(new FileWriter("out.txt")); 

    out.write(ran.toString()); 
    out.flush(); 
    out.close(); 
+0

我不明白。你能显示你的toString方法吗?你正在做一个for循环,在模5的索引上有一个if? – Abundance

+0

是,种,这是我的toString() 公共字符串的toString() \t { \t \t的for(int i = 0; I Linksx

如果有get(int i)功能,我会写toString如下:

public String toString(){ 
    String ans = ""; 
    for(int i = 0; i < this.length; i++){ 
      ans += this.get(i) + " "; 
      if(i % 5 == 0) 
       ans += "\n"; 
    } 
    return ans; 
} 

这是你会怎么写get(int i)

public int get(int index){ 
    Node head = this.head; 
    for(int i = 0; i < index; i++){ 
     head = head.next; 
    } 
    return head.getData(); 
} 
+0

感谢您的建议@Andundance,但我没有get(int i)函数。我只有“节点”数据类型和一个“int大小” – Linksx

+0

你可能有一个Node next()函数或字段吗?另外,如何访问节点中的数据值?它是node.data吗? – Abundance

+0

是的,我有一个节点next和prev。在DLL中我有int大小; int节点头; int节点结束,和node.getData(); – Linksx

如果它只是使用这个格式。

for(int i=0; i<100; i++) 
{ 
    Integer n = new Integer((int) (Math.random()*100)); 
    ran.startValue(n);  //this is my add function, to add elements in list 
    System.out.print(n+" "); 

    if(i%5==0)System.out.println(""); 
} 

但我同意@Hovercraft应该使用PrintWriter,它也提供默认的换行打印方法。无需重写的toString()这里

+0

谢谢你,和@Hovercraft,我会尝试与PrintWriter和临时值计数器 – Linksx

+0

我更新:无需温度,因为你已经有变量我 –

使用提供您的节点和DLL函数,你也许可以做这样的事情在你的DLL类:

public String toString(){ 
    String ans = ""; 
    Node head = this.head; 
    for(int i = 0; i < this.size; i++){ 
     ans += head.getData() + " "; 
     if(i % 5 == 0) 
      ans += "\n"; 
     head = head.next; 
    } 
    return ans; 
} 

这将是同样容易在一个while循环来写如下:

public String toString(){ 
    String ans = ""; 
    Node head = this.head; 
    int i = 1; 
    while(head != null){ 
     ans += head.getData() + " "; 
     if(i % 5 == 0) 
      ans += "\n"; 
     head = head.next; 
     i++; 
    } 
    return ans; 
} 
+0

我想感谢你的努力解决我的问题,这段代码没有错误,但是当我调用:out.write(ran.toString())时,我的out.txt中的数字仍然位于同一位置,全部位于同一行中。我的老师 – Linksx

+0

给了我一个提示。他这样说:在DLL类中创建一个函数:public DLL GetElementFrom(index i),并使用以下代码调用此函数:for(int i = 0; i Linksx

+0

我很惊讶它仍然给出相同的输出,尽管放置了换行符。 – Abundance