【问题标题】:Java: random number is the same for everythingJava:随机数对所有事物都是相同的
【发布时间】:2013-10-10 05:42:20
【问题描述】:
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]);
    }

}


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

【问题讨论】:

  • 提问的地方不在这里。
  • 你需要循环遍历数组并在每一个时间分配一个随机值
  • 您为每个元素分配了相同的编号,因此它们是相同的。

标签: java arrays random


【解决方案1】:

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

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);
}

【讨论】:

    【解决方案2】:

    每次您想要生成一个新的随机数时都需要调用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);
    

    【讨论】:

      【解决方案3】:

      您正在为 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]);
      
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 2017-04-03
        • 1970-01-01
        相关资源
        最近更新 更多