当我运行程序时,最小的数字总是为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);
}
}
}
在读取每个值时,您正在对数组进行排序。
for(int i = 0; i < 100; i++) {
sort[i] = ooss.readInt();
Arrays.sort(sort);
}
这意味着你从[1,0,0,0,...]开始,但排序后你有[0,0,0,... 1]
这是调试器可以帮助您调试程序的地方。解决方案是在读取数组后才对数组进行排序。
一个更简单的解决方案是一次写入和读取数组,而不是使用循环。
顺便说一下:除非你正在编写/阅读对象,否则你不需要使用ObjectOutputStream,与DataOutputStream相比,它有一个开销。
正如@KevinEsche指出的那样,如果你有100个0到99的随机值,那么其中一个很可能会为0,尽管不是每次都有。
较短的实现可能如下所示
public static void main(String[] args) throws IOException {
Random rand = new Random();
int samples = 100;
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("test"))) {
out.writeInt(samples);
for (int i = 0; i < samples; i++)
out.writeInt(rand.nextInt(100));
}
int[] sort;
try (DataInputStream in = new DataInputStream(new FileInputStream("test"))) {
int len = in.readInt();
sort = new int[len];
for (int i = 0; i < len; i++)
sort[i] = in.readInt();
}
IntSummaryStatistics stats = IntStream.of(sort).summaryStatistics();
System.out.println("The largest number in the file is: " + stats.getMax());
System.out.println("The smallest number in the file is: " + stats.getMin());
System.out.println("The average number in the file is: " + stats.getAverage());
}