0

所以我有一个 Java 程序,它生成 100 个 0 到 9 之间的随机整数,我需要计算生成整数的最大、最小和平均数。到目前为止我有

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

这是我想要的,但最大数量部分很奇怪。它打印出该行很多次,我如何使它只打印一次?

4

1 回答 1

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);
于 2013-05-07T22:01:34.740 回答