Dodo
Dodo

Reputation: 103

How to replace single element of array

I will have a series of random arrays similar to.

array1[] = {1,2,3,0,0,5,6}
array1[] = {1,2,0,0,4,5,6}

I want them to end up like, so I replace the first 0 with X.

array1[] = {1,2,3,X,0,5,6}
array1[] = {1,2,X,0,4,5,6}

the code I'm using replaces all zeroes giving instead of just one.

array1[] = {1,2,3,X,X,5,6}
array1[] = {1,2,X,X,4,5,6}

Which isn't what I'm looking for. I'd be happy just replacing either one but only one. The code I'm using,

for(int i=0; i<array.length; i++){
        if(fruit[i] == 0)
            fruit[i]=X;
    }

Hope that was clear, thanks for any help! Being stuck at this for a little while now.

Upvotes: 1

Views: 993

Answers (1)

David Xu
David Xu

Reputation: 5597

Try using break.

for(int i = 0; i < array.length; i++) {
    if(fruit[i] == 0) {
        fruit[i] = X;
        break;
    }
}

This will ensure only one is changed, max.

Upvotes: 2

Related Questions