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]);
}
}
问题:每个元素都有相同的值,但我希望每个元素都有随机和不同的值。
答案 0 :(得分: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);
}
答案 1 :(得分: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);
答案 2 :(得分: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]);
}
}