【发布时间】:2014-11-10 19:41:26
【问题描述】:
我是一个新手 android 程序员。
我正在尝试创建一个简单的游戏。
游戏;
显示一个介于 1 到 10 之间的随机数,我们说它是 mainnumber。 显示 4 个按钮。 第一个按钮值是 mainnumber。 第二个按钮值为 mainnumber + 1 第三个按钮值是 mainnumber - 1 最后一个按钮的值为 mainnumber + 2
怎么玩; 如果用户点击了正确的按钮(mainnumber),它将显示另一个数字和按钮。
我的代码;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easygame);
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int mainnumber = number.nextInt(10)+1;
int rnd1 = mainnumber + 1;
int rnd2 = mainnumber + 2;
int rnd3 = mainnumber - 1;
String a = Integer.toString(mainnumber);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(mainnumber));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Random rand = new Random();
buttons.get(rand.nextInt()).setText(texts.get(rand.nextInt()));
}
出现系统错误,并关闭应用程序。
问题; 如何每次随机显示按钮,如何检查单击的按钮是否为真按钮。
谢谢...
【问题讨论】:
-
您需要显示更多的日志记录和错误消息,但我会说您会收到某种 OutofBoundsException 异常,因为您的 Random 对象不受任何限制并且可能返回 8,675,309大于您的文本数组列表。
-
@Dave 它实际上以 10 为界。
-
此 Random 实例不受限制:Random rand = new Random(); button.get(rand.nextInt()).setText(texts.get(rand.nextInt()));
-
哦,当然!对不起。这支持了你的怀疑。
-
是的,以 java.lang.IndexOutofBoundsException 开头的错误
标签: android arrays random arraylist