如何使数组的对象都包含整数数组?

时间:2013-02-27 04:19:47

标签: java arrays object

这是一个让我头脑发热的想法,但我认为这里有人能够恰当地说明这一点。基本上,我有一个for循环运行,增加了对象数组。我希望每个对象都能保存记录的数组。

static RollDice p1,p2,p3,p4;
static RollDice[] Players = new RollDice[]{p1,p2,p3,p4};
for (int a=0;a<4;a++){

  for(int b =0;b<4;b++){
        roll = Math.random()*5;
        roll = Math.round(roll);
        roll = roll+1;
        Players[a].Numbers[b]=(int)roll;
        System.out.println("You have rolled a: "+roll);
  }
        //This prints four numbers in an array for each value of a.
        System.out.println(Arrays.toString(Players[a].Numbers));
       //This is SUPPOSED to call the numbers recorded for that object. I had it as Players[#].Numbers before, but of course that didn't work either.
        System.out.println(Arrays.toString(p2.Numbers));

所以我想我在问我是否应该继续,或者只是不浪费我的时间。还请把它拼出来,就像我是个白痴一样,因为我是。

2 个答案:

答案 0 :(得分:0)

class RollDice
{
    public int [] Numbers = new int [4];
}

RollDice p1,p2,p3,p4;
// Do not foget to initialize p1, p2, p3, p4 here
RollDice [] Players = new RollDice [] {p1, p2, p3, p4};
Players [2].Numbers [3] = 4;

答案 1 :(得分:0)

我认为这应该可以解决问题: -

RollDice p1 = new RollDice(), p2 = new RollDice(), p3 = new RollDice(), p4 = new RollDice();
RollDice[] players = new RollDice[] { p1, p2, p3, p4 };

for (int a = 0; a < 4; a++) {
    int roll = 0;
    for (int b = 0; b < 4; b++) {
        roll = (int) Math.round(Math.random() * 5);
        roll++;
        players[a].numbers[b] = roll;
        System.out.println("You have rolled a: " + roll);
    }
    System.out.println(Arrays.toString(players[a].numbers));
}

class RollDice{
    public int [] numbers = new int [4];
}

注意: - 我已将变量名称从uppercase更改为lowercase,以获得更好的命名约定。