【问题标题】:Android - Random int isn't randomAndroid - 随机 int 不是随机的
【发布时间】:2015-02-17 02:31:51
【问题描述】:

目前,我有三组不同的图像,它们是使用随机整数字符串随机生成的。 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");
}

【问题讨论】:

标签: android random int


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 2012-10-04
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2014-10-07
    • 2014-04-27
    • 2017-10-17
    相关资源
    最近更新 更多