我将12个ImageButtons分配给他们自己的id,然后给每个6个随机图像。我想要6对2.我创建了自己的类“Pairs”来存储它们但它崩溃了 我遗漏了一些初始化只是为了避免集群,但这是基本设置
class Pairs {
int first;
int second;
public void setFirst(int a){
first = a;
}
public void setSecond(int a){
second = a;
}
}
protected void onCreate(Bundle savedInstanceState){
Boolean isShown[];
Pairs imagePairs [] = new Pairs[6];
gen = new Random();
int randomAssign = 1;
while(randomAssign < 13){
b = gen.nextInt(12) + 1;
while(isShown[b] == true){
b = gen.nextInt(12) + 1;
}
if (randomAssign < 2){
buttons[b].setImageResource(R.drawable.img01);
imagePairs[0].setFirst(b);
}
else if (randomAssign <3){
buttons[b].setImageResource(R.drawable.img01);
imagePairs[0].setSecond(b);
}
else if (randomAssign < 4){
buttons[b].setImageResource(R.drawable.img02);
imagePairs[1].setFirst(b);
}
else if (randomAssign <5){
buttons[b].setImageResource(R.drawable.img02);
imagePairs[1].setSecond(b);
}
else if (randomAssign < 6){
buttons[b].setImageResource(R.drawable.img03);
imagePairs[2].setFirst(b);
}
else if (randomAssign <7){
buttons[b].setImageResource(R.drawable.img03);
imagePairs[2].setSecond(b);
}
else if (randomAssign < 8){
buttons[b].setImageResource(R.drawable.img04);
imagePairs[3].setFirst(b);
}
else if (randomAssign < 9){
buttons[b].setImageResource(R.drawable.img04);
imagePairs[3].setSecond(b);
}
else if (randomAssign < 10){
buttons[b].setImageResource(R.drawable.img05);
imagePairs[4].setFirst(b);
}
else if (randomAssign < 11){
buttons[b].setImageResource(R.drawable.img05);
imagePairs[4].setSecond(b);
}
else if (randomAssign < 12){
buttons[b].setImageResource(R.drawable.img06);
imagePairs[5].setFirst(b);
}
else if (randomAssign < 13){
buttons[b].setImageResource(R.drawable.img06);
imagePairs[5].setSecond(b);
}
isShown[b] = true;
randomAssign++;
}
}
答案 0 :(得分:1)
之间
Pairs imagePairs [] = new Pairs[6];
并且
imagePairs[0].setFirst(b);
你需要在某处初始化你的对:
imagePairs[0] = new Pairs();
如果你不这样做,imagePairs [0]将为null,你将得到一个NullPointerException ...... 显然,这同样适用于imagePairs [1],imagePairs [2]等。
编辑:这可以通过for循环来完成:
for(int i=0; i<imagePairs.length; i++){
imagePairs[i] = new Pairs();
}