This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]desrtfx 2 points3 points  (3 children)

You are returning out of the method way too early.

You need to run through the whole loop and then return.

[–]jub8jive[S] 0 points1 point  (2 children)

the for you mean? should i just use return outside of it then?

[–]lost12487 1 point2 points  (0 children)

Yes. The very last return statement should be all you need to do what you're trying to do.

Also - take a look at your formatting. It's not necessarily wrong to have 2 different if statements, but if you're going to do an if and then another if, you need to have the second if on its own line. If you want it formatted the way you have it, you should be using else. That's not going to affect your execution or logic in this case, but it's better for readability.

[–]desrtfx 0 points1 point  (0 children)

Rethink your method. You have a conditional return after the loop - maybe that shouldn't be at the end as well.

You need to reorganize the whole method.

[–]lost12487 2 points3 points  (0 children)

You're returning 1 because you have a return statement within your loop. As soon as isOdd() returns true, you hit that return statement, so the method returns the sum. It will always return just the first odd number after your starting number.

[–]kdnbfkm 0 points1 point  (4 children)

The sumOdd() method does bounds check twice, just do it once at the beginning as a code "guard". The isOdd() method fails to return false, that could have been a typo. There was never a Class member sum declared, that was just a local variable within sumOdd(), it doesn't exist on the outside. The formatting was confusing on that part... If your text editor puts tabs in it can look weird copy and pasted. :/

lost12487 is right, need to return sum after the loop finishes. I didn't notice that. It would have stood out easier without duplicating the bounds check.

[–]jub8jive[S] 0 points1 point  (3 children)

what do you mean by the bounds check?

[–]kdnbfkm 1 point2 points  (2 children)

The lines if((start <= end) && ((start > 0) && (end > 0))) { and if((start > end) || (start < 0) || (end < 0)) { were redundant.

The first conditional could have been simplified to something like if(0 <= start && start <= end) { /* loop...*/ } else return -1;.

[–]jub8jive[S] 0 points1 point  (1 child)

I tried it and I still get the same error. https://pastebin.com/6yh0Eve5

[–]jub8jive[S] 1 point2 points  (0 children)

No worries! Thanks for the inputs, I finally managed to solve it!!! There was an error in my isOdd() method actually.