我为我的一个班级写了一个简短的程序,有些东西是我无法弄清楚的。所以我应该在一个文件上写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();
}
非常感谢,非常感谢任何帮助!
答案 0 :(得分:1)
使用Scanner input = new Scanner(file);
打印值后,使用output.flush()
保存数据。
output.close()
- 将关闭您的信息流,但您将无法存储已排序的值。
// 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 + " ");
}
output.flush();
答案 1 :(得分:0)
您需要关闭输出流才能将其写入文件。你第二次正确地这样做了,但不是第一次。
添加:
output.close();
后:
// 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 + " ");
}
//Here close the first output stream to get the data to the file.
output.close();
答案 2 :(得分:0)
在下面的代码行之前,您需要close
或flush
将您的内容写入您的文件。
output.close(); <--- you need to close here
Scanner input = new Scanner(file);
因为,直到上面的代码行,没有任何内容写入文件。所以,下面的代码变得无用
while (input.hasNext()) { // nothing to read
sortedList.add(input.nextInt()); //nothing added to List
}
//Sorting elements from array list
Collections.sort(sortedList); //nothing to sort
// Printing the elements in increasing order
for (int i = 0; i < sortedList.size(); i++) {
output.print(sortedList.get(i)); // won't execute this line
}