我正在制作这个应用程序,每次用户点击当前卡片的图像时,随机播放卡片并显示随机卡片。我制作了一个包含所有卡片图像的数组,并使用了“Fisher Yates Shuffle'洗牌阵列。这是我写的代码:
public class MainActivity extends Activity {
int[] cards={R.drawable.aceofspades,R.drawable.aceofhearts,R.drawable.aceofclubs};{
int i = cards.length, j, temp;
while(--i > 0){
j = (int) Math.floor(Math.random() * (i+1));
temp = cards[j];
cards[i] = cards[j];
cards[i] = temp;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void imageClick(View view) {
{
ImageView image = (ImageView) findViewById(R.id.imageDice1);
image.setImageResource(cards); // This gives an error: change type of 'cards' to 'int'.
}
}
}
问题是,我不知道如何设置' image.setImageResource'。它应该是第一个混洗卡阵列,当用户点击它时,它应该成为数组中的下一个(类似于i ++)。 我试过卡片#39;但它给了我一个错误。 '卡[I]'也不起作用。可能是什么问题?
答案 0 :(得分:0)
条件循环从不存在于将while loop
置于函数
类似这样的事情
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
while(--i > 0){
j = (int) Math.floor(Math.random() * (i+1));
temp = cards[j];
cards[i] = cards[j];
cards[i] = temp;
}
}
答案 1 :(得分:0)
尝试这样的事情。
public class MainActivity extends Activity {
int currentCardIndex = 0;
int[] cards = { /* card drawables here */};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shuffle(cards);
}
public void imageClick(View view) {
ImageView image = (ImageView) findViewById(R.id.imageDice1);
image.setImageResource(cards[currentCardIndex++]);
}
private void shuffle(int[] array) {
int idx, tmp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
idx = random.nextInt(i + 1);
tmp = array[idx];
array[idx] = array[i];
array[i] = tmp;
}
}
}