我想多次重复一个程序。我如何将这些结果记录在另一个类中

时间:2017-02-11 01:15:03

标签: java

import java.util.Random;
public class test{
public static void main(String[] args){

    System.out.println(qq(30));
}

public static int qq(int range){ 
    Random generator=new Random();
    int[] aa = new int[range];     //create an array with "range" elements
    for (int w=0;w <range;w++) {
        aa[w] = generator.nextInt(20);// assign random numbers to array aa
    }
    int ee=0; //number of times 
    outerloop:
    for(int i =0;i<range;i++){
        for(int j=i+1;j<range-1;j++){
            if (aa[i]==aa[j] ){
                break outerloop;//if aa[i] and aa[j] are the same,break and return ee

            }
            else{
                ee++; //if aa[i] and aa[j] are not the same, ee++ and keep going 
            }
        }
    }
    return ee;//return the min number of failed match attempts

}
}

我想重复这个程序10次(收到10&#34; ee&#34; s),我如何创建另一个类来保存这些结果,以便我可以使用这10个数字来找到平均值。

1 个答案:

答案 0 :(得分:0)

您可以将结果存储在List或Array中。您不必创建另一个类,您可以使用内置的实用程序类或数组来实现您的目标。 要在List中存储值,请按以下步骤替换主方法体。

java.util.List<Integer> l=new java.util.ArrayList<>();
int sum=0;
for (int i=0; i<10; i++){
    int a=qq(30);
    l.add(a);
    sum+=a;
}
System.out.print(sum);

如果要使用以下主要方法的整数替换主体的数组。

int ar[]=new int[10];
int sum=0;
for (int i=0; i<ar.length; i++){
    int a=qq(30);
    ar[i]=a;
    sum+=a;
}
System.out.print(sum);

如果您不想存储结果&amp;只是对你感兴趣而不是你不必使用ArrayList。 你可以尝试这个。

int sum=0;
for (int i=0; i<ar.length; i++)
    sum+=qq(30);
System.out.print(sum);