[英]I get an ArrayIndexOutOfBoundsException in my code
The output of the Android's logcat
informs me that an ArrayIndexOutOfBoundsException
is thown at some point in my program : Android的
logcat
的输出通知我程序中的某个时刻抛出了ArrayIndexOutOfBoundsException
:
I have set up a boolean value for the button earlier, the button is for testing purposes. 我之前为按钮设置了布尔值,该按钮用于测试目的。
This is the code in which believe the error is located : 这是认为错误所在的代码:
int hour = new Date().getHours();
int min = new Date().getMinutes();
int secs = new Date().getSeconds();
String date = hour + ":" + min+ ":" + secs;
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bSet = true;
}
});
while (date =="01:00:00" || bSet == true);
int randomNumber = rand.nextInt();
tv.setText(getResources().getString(ids[randomNumber]));
I think you have exception in last line. 我认为您在最后一行有例外。 Exactly here
ids[randomNumber]
正是在这里
ids[randomNumber]
You should check random generated number, because it can be greater then ids.length. 您应该检查随机生成的数字,因为它可以大于ids.length。 Use
rand.nextInt(ids.length);
使用
rand.nextInt(ids.length);
It will generate random number from 0 to ids.length. 它将生成从0到ids.length的随机数。
For better practice change 为了更好的实践改变
while (date =="01:00:00" || bSet == true);
as 如
while (date.equals("01:00:00") || bSet)
And change int randomNumber = rand.nextInt();
并更改
int randomNumber = rand.nextInt();
as int randomNumber = rand.nextInt(ids.length);
作为
int randomNumber = rand.nextInt(ids.length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.