-2

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?

1
  • 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.
    – AjayGohil
    Commented Feb 1, 2021 at 3:41

2 Answers 2

0

The cases where you would use an ordinary loop over a for-each loop are quite rare. In most cases, you should stick with the usual for-each loop specifically because it prevents you from do the sort of mistakes you have here, where you try to reach an element outside the array.

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.

0
0

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.

What to do?  Stop the loop short of the last element.  Decide if or how you want to handle the last element, because you can't compare it to the next.

2
  • Thank you so much for taking the time to respond! So I would have to create another for loop for the last element? I.e. for(i=0; i<n-1;i++). If I do this, what parameter would I have to put in to print out the last value? arr[n-1] or arr[i-1]?
    – Y3LLZ
    Commented Jan 30, 2021 at 17:38
  • What do you want do compare the last element to?
    – Erik Eidt
    Commented Jan 30, 2021 at 20:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.