How can I check if there's another value in a String array without exiting a for loop if there is?

Viewed 36

I was wondering if there's a way to essentially look at the next position of a string index and determine if there's a value stored at that index, without being broken out of the loop with an exception if there isn't one?

String[] indexesList = new String[] {"Group 1", "MEAN", "Group 2", "SDEV"}
for(int inside = 2; inside < indexesList.legth; inside += 2) {
   statementA.setObject(7, indexesList[inside]); 
   statementA.setObject(8, indexesList[inside + 1]);
}

With The previous snippet will throw an java.lang.ArrayIndexOutOfBoundsException: Index x out of bounds for length 4 error, and I was wondering if there's a way to accomplish going through each value in the list, check if there's another value present while on the current iteration, and continue without any exceptions if there isn't another value?

1 Answers

I am not sure I understand your loop as you start at index 2 (which is position 3) then increment by two, so not too clear to me what you are trying to accomplish.

However, one thing right off the bat I see is that inside your block you are checking for indexesList[inside + 1]. This will throw java.lang.ArrayIndexOutOfBoundsException when you reach the end of the array and try to access the next element which does not exist.

To remedy that, in your for loop set a condition to make sure the iteration stops a position before the last like so inside < indexesList.legth - 1.

Related