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();
如果有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();
}
如果它只是使用这个格式。
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()这里
谢谢你,和@Hovercraft,我会尝试与PrintWriter和临时值计数器 – Linksx
我更新:无需温度,因为你已经有变量我 –
使用提供您的节点和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;
}
我不明白。你能显示你的toString方法吗?你正在做一个for循环,在模5的索引上有一个if? – Abundance
是,种,这是我的toString() 公共字符串的toString() \t { \t \t的for(int i = 0; I Linksx