CodingBat AP-1 scoresIncreasing练习题中return false与score=false的差异及问题原因问询
return false; vs score=false; in Your scoresIncreasing Solution Let's start by breaking down what your original code does correctly, then dive into why changing that line breaks things.
First, the original code logic
Your working solution checks each pair of consecutive scores:
- For every
i, ifscores[i+1] >= scores[i], it setsscore = true(though this is actually redundant, we'll get to that later). - If it finds any pair where
scores[i+1] < scores[i], it usesreturn false;to immediately exit the method and returnfalseto the caller. - If the loop finishes without hitting that
return, it means all pairs are valid, so it returnsscore(which will betrueafter the last valid pair).
The key difference between return false; and score=false;
return false;:
This does two critical things: it sets the method's return value tofalse, and it stops all execution of the method right away. As soon as you hit this line, the loop breaks, no more iterations run, and your method gives backfalse—which is exactly what you want, because you've already found evidence the array isn't increasing.score=false;:
This only updates the value of thescorevariable tofalse—it doesn't stop the loop or the method. The program will keep running the next iterations of the loop. Here's where the bug happens:- Suppose you have an array like
[1, 3, 2, 4]. Wheni=1,scores[2] = 2is less thanscores[1] = 3, soscoregets set tofalse. - But the loop doesn't stop! Next iteration,
i=2,scores[3] =4 >= scores[2] =2, soscoregets set back totrue. - By the end of the loop, you return
true—even though the array has a decreasing pair, which is totally wrong.
- Suppose you have an array like
A quick side note on your original code
You don't actually need the score variable at all! If the loop completes without hitting a return false;, that means every consecutive pair is valid. So you could simplify the method to:
public boolean scoresIncreasing(int[] scores) { for(int i = 0; i < scores.length-1; i++){ if(scores[i+1] < scores[i]){ return false; } } return true; }
This works the same way, but it's cleaner and avoids any confusion with the score variable.
内容的提问来源于stack exchange,提问作者Mateusz

