如何将一个int放回Java中的数组中

时间:2014-11-09 01:35:59

标签: java arrays random

    // This code lets the computer select the first random number from your array
  int rn1 = boarduser[new Random().nextInt(boarduser.length)];
    System.out.println("Computer's Value: " + rn1);

    // This code lets the computer select the second random number from your array      
  int rn2 = boarduser[new Random().nextInt(boarduser.length)];
    while (rn2 == rn1) // this code checks for another value in the array if the number generated was previously selected
    {
        rn2 = boarduser[new Random().nextInt(boarduser.length)];
    }
    System.out.println("Computer's Value: " + rn2);
    // This code lets the computer select the third random number from your array       
  int rn3 = boarduser[new Random().nextInt(boarduser.length)];
    while (rn3 == rn1 || rn3 == rn2)
    {
        rn3 = boarduser[new Random().nextInt(boarduser.length)];
    }
    System.out.println("Computer's Value: " + rn3);
    // turning the tokens chosen face down on the grid (changing their values to 0)
    {
        rn1 = 0;
        rn2 = 0;
        rn3 = 0;
    }

基本上我试图让rn1 = 0将数组生成的随机值设置为0,但是当我打印数组时,数字似乎仍然保持不变。任何的想法?感谢

2 个答案:

答案 0 :(得分:0)

rn1 = 0仅在本地更改rn1的值,而不是在实际数组中。您必须将索引中的元素rn1分配给0而不是。

int rn1Index = new Random().nextInt(boarduser.length);
int rn1 = boarduser[rn1Index];
// ...
boarduser[rn1Index] = 0;

答案 1 :(得分:0)

将随机索引保存到变量中并将其用于" zerofy"读取后该数组中的项目:

int index = new Random().nextInt(boarduser.length)
int rn1 = boarduser[index];
boarduser[index] = 0; // you need this line