【发布时间】:2016-02-16 12:46:27
【问题描述】:
当我运行程序时,最小的数字always原来是0。这是为什么呢?最大值和平均值似乎是正确的。
问题很可能在于我如何使用随机类。
import java.io.*;
import java.util.*;
import java.util.Arrays;
public class ReadAndWrite {
public static void main(String[] args) {
Random ran = new Random();
int i_data = 0;
int[] sort = new int[100];
File file = new File("Test4");
int total = 0;
int average = 0;
try {
file.createNewFile();
}
catch(Exception e) {
System.out.println("Could not create the file for some reason. Try again.");
System.exit(0);
}
try {
FileOutputStream fos = new FileOutputStream("Test4");
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i = 0; i <= 100; i++) {
int x = ran.nextInt(100);
oos.writeInt(x);
}
oos.close();
}
catch(IOException e) {
System.out.println("Whoops");
}
try {
FileInputStream fos = new FileInputStream("Test4");
ObjectInputStream ooss = new ObjectInputStream(fos);
for (int i = 0; i < 100; i++) {
sort[i] = ooss.readInt();
}
Arrays.sort(sort);
for(int i = 0; i < 100; i++) {
total = total + sort[i];
average = total/100;
}
System.out.println("The largest number in the file is: " + sort[99]);
System.out.println("The smallest number in the file is: " + sort[0]);
System.out.println("The average number in the file is: " + average);
ooss.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
【问题讨论】:
-
为什么总是加一个数后排序?
-
你为什么要打电话给
Arrays.sort()100 次。也可能因为nextInt(100)而获得0。 -
好的,我已经多次运行该程序,最后得到了一个 1 作为我的最小值。 @Satya 感谢您指出这一点。我错误地将 Arrays.sort() 放入循环中。