【发布时间】:2017-08-22 23:47:44
【问题描述】:
我为我的一个班级编写了一个简短的程序,但有些东西我无法弄清楚。所以我应该在文件上写入 100 个随机整数,读回数据并按递增顺序打印整数。一切正常,但我没有在输出文件中看到我的最终排序列表,任何人都可以看到为什么?
这是我的代码:
private final static int NUMBEROFRANDOM = 100;
public static void main(String[] args) throws IOException {
// Creating my file
java.io.File file = new java.io.File("Question1.txt");
// If it already exists, print a message and terminate program
if (file.exists()) {
System.out.println("File already exists.");
System.exit(0);
}
// Creating my PrintWriter object
PrintWriter output = new PrintWriter(file);
// Creating 100 random numbers between 0 and 100 and printing them on the file
for (int i = 0; i < NUMBEROFRANDOM; i++) {
int number = (int) (Math.random() * 101);
output.print(number + " ");
}
// Creating my Scanner object
Scanner input = new Scanner(file);
// Creating my array list to store the sorted list of 100 elements
ArrayList<Integer> sortedList = new ArrayList<Integer>();
// Reading the elements from the file and adding them into my array list
while (input.hasNext()) {
sortedList.add(input.nextInt());
}
//Sorting elements from array list
Collections.sort(sortedList);
// Printing the elements in increasing order
for (int i = 0; i < sortedList.size(); i++) {
//System.out.println(sortedList.get(i));
output.print(sortedList.get(i));
}
// Closing my objects
input.close();
output.close();
}
非常感谢,任何帮助都非常感谢!
【问题讨论】:
-
创建数字后需要关闭输出。
-
我看到有人打败了我 - 我的机器打开 IDE 的时间太长了 :)
标签: java io output writer reader