【发布时间】:2013-05-06 20:20:00
【问题描述】:
我需要解决这样的任务:
- 随机生成数组的长度 - 将此 int 保存到文件 ("input.txt)" 作为第一个数字;
- 随机生成数组元素 - 将每个元素保存到文件中(“input.txt”)
但数组元素不会保存到文件中。
正如我从控制台数组中看到的,有数字,但它们没有保存到文件中。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
Random rand;
Scanner sc;
PrintWriter pr, pr2;
public void run() throws FileNotFoundException {
pr2 = new PrintWriter(new File("input.txt"));
pr = new PrintWriter(new File("output.txt"));
rand = new Random();
int a = rand.nextInt((int) Math.pow(10, 3));
System.out.println(a);
pr2.print(a);
pr2.close();
sc = new Scanner(new File("input.txt"));
int[] arr = new int[a];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt((int) Math.pow(10, 3));
}
for (int i = 0; i < arr.length; i++) {
System.out.println("" + i + ": " + arr[i]);
pr2.print(arr[i]);
}
pr2.close();
return;
}
}
【问题讨论】:
-
你关闭 pr2 然后尝试写入它。去掉 sc = new Scanner(new File("input.txt")) 之前的语句,关闭 writer。
标签: java arrays io printwriter