2013-02-27 59 views
0

这是一个超越我的想法,但我认为这里的某个人可以正确地说明它。基本上,我有一个循环运行,增加对象数组。我想要每个对象来保存录制的数组。如何让数组中的对象包含整数数组?

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

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

回答

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

注: -我已经改变了变量名,从uppercaselowercase更好的命名约定。

+0

哇,我想我不能使用静态的一切然后。谢谢你。 – user2076744 2013-02-27 05:29:38

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; 
相关问题