所以我有一个Java程序,在0到9之间生成100个随机整数,我需要计算生成的整数的最大,最小和平均数。到目前为止我已经
了import java.util.Random;
public class World {
public static void main(String[] args) {
public void generateNumber() {
System.out.println("Generating 100 random integers between 0 and 9");
Random aGenerator = new Random();
int randomArray[]=new int[101];
int countArray[]=new int[10];
//generate the numbers and store into an array
int j;
for (int i=1; i<101; ++i) {
j=i;
randomArray[i]=aGenerator.nextInt(10);
//displaying numbers
System.out.println("Number " + j + " = " + randomArray[i]);
}
int max = randomArray[0];
for (int i=1; i<randomArray.length; i++) {
if (randomArray[i] > max) {
max = randomArray[i];
}
System.out.println("Max number is "+ max);
}
}
}
}
打印出来:
Generating 100 random integers between 0 and 9
Number 1 = 2
Number 2 = 9
Number 3 = 3
...
Number 99 = 4
Number 100 = 8
这是我想要的,但最大数字部分很奇怪。它打印出那条线很多次,我怎么做它只打印一次?
答案 0 :(得分:1)
它打印的次数与for
循环的次数相同,因为该语句在循环中。
你想要的是:
int max = randomArray[0];
for(int i=1; i<randomArray.length; i++) {
if(randomArray[i] > max){
max = randomArray[i];
}
}
System.out.println("Max number is "+ max);