简体   繁体   中英

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 :

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]

You should check random generated number, because it can be greater then ids.length. Use rand.nextInt(ids.length); It will generate random number from 0 to 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();

as int randomNumber = rand.nextInt(ids.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM