# Comparing and replacing values in an array [closed]

I am currently working on a program that replaces the value in an array if the value next to it is the same as the current value. So If the array is `[0,0,0,1,0,1,0]`, when the program runs it'll turn to `[0,0,1,1,1,1,1]`. Currently, the code works to an extent, it runs but I still get an “Index out of bounds exception” after it terminates, and it prints out one less value than it should. So an array that had 5 elements ends up having 4 elements. Here's my code:

``````int arr[] = {0,1,0,0,1,0,0};

int days = 0;
int arr[] = {0,1,0,0,1,0,0};
do {
int n = arr.length;
for(int i=0; i<arr.length; i++) {//iterates through the array and subs in 0s for duplicates and 1s for regulars
if(arr[i] == arr[i+1]) {
arr[i] = 0;
}else{
arr[i] = 1;
}

System.out.println(" "+arr[i]);
}

days++;
}while(days<=30);
``````

What can I do to fix that issue and stop the error after the program runs?

• For the last element in for each loop arr[i+1] is out of index because for last element i=6 and arr[i+1]=arr[7] which is index out of bound because the element in the array is 7 so 6 comparisons are done .for last element you can put 1 or you can use for each loop. Commented Feb 1, 2021 at 3:41

What happens in your case is that at the very last iteration, `i` corresponds to the last element in the array. Then, you do `arr[i+1]`, that is, ask to get a value just after the very last value. This is where you get the expected “Index out of bounds exception.”
Instead, rewrite your code with `for (int x : ar)`. Since you need to evaluate two adjacent elements, you'll also need a local variable `int previous` which would remember the previous value from the array. It's up to you to decide what should be the initial value for this variable.
Your loop takes `i` through every position in the array.  That means that `i+1` is going to be out of bounds when `i` refers to the last element.