Dan
Dan

Reputation: 2344

Set a parameter based on an exception?

I have a FOR loop as below:

for (int i=0; i<DataTimes.length; i++) {

    int resultCounter = 0;
    int currentTime = DataTimes[i];
    int nextTime = DataTimes[i+1];
 }

I haven't included the entire code. This array has upwards of 1700 entries. My Android app crashes as I believe when I get to the end of the array "DataTimes[i+1]" is going to fail as the entry will not exist.

How can I account for this?

Something like when ArrayOutOfBound exception set nextTime to zero.

Thanks

Upvotes: 0

Views: 36

Answers (2)

DiogoSantana
DiogoSantana

Reputation: 2434

Change the line:

int nextTime = DataTimes[i+1];

To:

int nextTime = (i + 1) < DataTimes.length ? DataTimes[i+1] : 0;

Upvotes: 3

cnflat
cnflat

Reputation: 1

i must be error. DataTimes[i] is the last element in the array when i=DataTimes.length-1. At this time i+1 is really out of bound.

Upvotes: 0

Related Questions