1

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.

4
  • docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html Commented Jul 27, 2014 at 9:22
  • I've also tried to sort the array so the first element is 0 and then it's easy to replace but that doesn't work when X is a negative number, which it will be sometimes in this case. Commented Jul 27, 2014 at 9:22
  • 1
    I see no need to downvote this question. Despite it's simple answer Dodo has clearly put some work in here to describe it properly. So +1 for good formulated quertion. Commented Jul 27, 2014 at 11:55
  • (But don't forget to accept the ansert!) (the green checkmark left to the correct answer's rating) Commented Jul 27, 2014 at 11:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! I tried this earlier but I forgot the curly brackets in the if statement.. feel like an idiot but glad it's sorted. Thanks!
@Dodo Don't forget to accepot the answer :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.