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]);
}
}
Run Code Online (Sandbox Code Playgroud)
问题:每个元素都有相同的值,但我希望每个元素都有随机和不同的值.
多数民众赞成因为你已经分配了相同的价值
array[0]=randnumb;
array[1]=randnumb;
array[2]=randnumb;
array[3]=randnumb;
array[4]=randnumb;
Run Code Online (Sandbox Code Playgroud)
你需要这样做
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);
Run Code Online (Sandbox Code Playgroud)
或者你可以用更好的方式做到这一点
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);
}
Run Code Online (Sandbox Code Playgroud)
并且您可以使用访问这些值
for (int i : arr) {
// do whatever you want with your values here.I'll just print them
System.out.println(i);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |