-3
import java.util.Random;

class Moo {

    public static void main(String[] args) {
        Random rand = new Random();

        System.out.println("Index\tValue");
        int randnumb = 1 + rand.nextInt(11);
        int array[] = new int[5];

        array[0] = randnumb;
        array[1] = randnumb;
        array[2] = randnumb;
        array[3] = randnumb;
        array[4] = randnumb;

        for (int counter=0; counter < array.length; counter++)
            System.out.println(counter + "\t" + array[counter]);
    }

}


问题:每个元素都有相同的值,但我希望每个元素都有随机和不同的值。

4

3 回答 3

7

那是因为您分配了相同的值

array[0]=randnumb;
array[1]=randnumb;
array[2]=randnumb;
array[3]=randnumb;
array[4]=randnumb;

你需要做

array[0]=1+rand.nextInt(11);
array[1]=1+rand.nextInt(11);
array[2]=1+rand.nextInt(11);
array[3]=1+rand.nextInt(11);
array[4]=1+rand.nextInt(11);

或者你可以用更好的方式来做

Random randomNum = new Random();
int[] arr = new int[5];

/*Iterate through the loop for array length and populate
  and assign random values for each of array element*/

for(int i = 0; i < arr.length; i++){
    arr[i] = randomNum.nextInt(11);
}

您可以使用访问这些值

for (int i : arr) {
     // do whatever you want with your values here.I'll just print them
    System.out.println(i);
}
于 2013-10-10T05:43:32.247 回答
3

nextInt()每次要生成新的随机数时都需要调用。所以做这样的事情:

Random rand = new Random();

System.out.println("Index\tValue");
// Don't need this anymore...
//int randnumb = 1+rand.nextInt(11);
int array[]= new int[5];

array[0]=1+rand.nextInt(11);
array[1]=1+rand.nextInt(11);
array[2]=1+rand.nextInt(11);
array[3]=1+rand.nextInt(11);
array[4]=1+rand.nextInt(11);
于 2013-10-10T05:45:47.583 回答
0

您正在为 randnumb 分配一个值并使用相同的值来初始化您的数组元素。尝试这个。

import java.util.Random;

class moo{
public static void main(String[] args){

Random rand = new Random();

System.out.println("Index\tValue");
int randnumb; 
int array[]= new int[5];
for(int j=0;j<=4;j++)
{
    randnumb=1+rand.nextInt(11);
    array[j]=randnumb;
}

for(int counter=0;counter<array.length;counter++)
        System.out.println(counter +"\t"+array[counter]);

}

}

于 2013-10-10T05:51:09.727 回答