当我运行程序时,最小的数字总是变成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());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句