当我运行程序时,最小的数字总是结果是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());
}
关于java - 为什么从我的文件中读取的最小数字总是 0? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35433044/