Android - Random int不是随机的

时间:2015-02-17 02:31:52

标签: android random int

目前,我有三组不同的随机整数字符串生成的图像。 str2和str3工作正常,但由于某些原因,当我使用rnd.nextInt(1)时,它只返回0.不是0和1,只有0.我对它进行了数百次的采样,每次它只是0。再次,其他两个字符串按预期随机返回。但是,如果我无法解决这个问题,我的应用程序将非常无聊。

我做错了什么或有没有更好的方法随机返回0和1?感谢所有帮助。

String str1 = "img_" + rnd.nextInt(1);
String str2 = "img_" + rnd.nextInt(2);
String str3 = "img_" + rnd.nextInt(3);
if (levelCounter <= 10) {imgView1.setImageDrawable(getResources().getDrawable(getResourceID(str1, "drawable", getApplicationContext())));
                    imgView1.setScaleType(ImageView.ScaleType.CENTER);
                    imgView1.setVisibility(View.VISIBLE);
} else if (levelCounter <= 18) {imgView1.setImageDrawable(getResources().getDrawable(getResourceID(str2, "drawable", getApplicationContext())));
                    imgView1.setScaleType(ImageView.ScaleType.CENTER);
                    imgView1.setVisibility(View.VISIBLE);
} else if (levelCounter >= 19) {imgView1.setImageDrawable(getResources().getDrawable(getResourceID(str3, "drawable", getApplicationContext())));
                    imgView1.setScaleType(ImageView.ScaleType.CENTER);
                    imgView1.setVisibility(View.VISIBLE);
} else {
                    Log.e(LOGCAT, "Counter Error: Unknown Level");
}

1 个答案:

答案 0 :(得分:0)

nextInt(n)返回0到n-1之间的随机数。如果您想要随机0或1,请使用nextInt(2)

相关问题