我在完成我的程序时遇到了一些麻烦。这是我得到的和说明。创建一个包含 500 个从 0 到 1000 的随机数的文件,使用 for 循环将数字写入文件。然后 1. 找到最小值 2. 找到最大值 3. 找到平均值 4. 确定连续数字出现的次数。我在创建随机数文件和第 4 步时遇到问题。提前致谢!
public static void main(String[] args) throws FileNotFoundException {
PrintWriter prw = new PrintWriter("results.txt");
File numfile = new File("randomdata.txt");
Scanner infile = new Scanner(numfile);
int num, largest, smallest, sum = 0, count = 0;
int programnumber = 6;
header (prw, programnumber );
double average = 0;
Random gen = new Random();
System.out.println("From gen: ");
for (int i = 0; i < 1000; i++){
System.out.print(gen.nextInt(500) + "");
num = gen.nextInt(500);
System.out.println(num);
sum = sum + num;
count++;
average = (double) sum / count;
}
while (infile.hasNext()){
num = infile.nextInt();
largest = infile.nextInt();
smallest = infile.nextInt();
System.out.println(num);
if (num < largest){
largest = num;
}
if (num > smallest){
smallest = num;
}
System.out.println("The largest is: " + largest);
prw.println("The largest is: " + largest);
System.out.println("The smallest is: " + smallest);
prw.println("The smallest is: " + smallest);
System.out.println("The average is: " + average);
prw.println("The average is: " + average);
}
prw.close();
}