保龄球计分循环代码调试求助:isNinetySix测试用例结果不符
It sounds like you're hitting a common snag with bowling score logic—off-by-a-few-points errors usually boil down to mishandling strikes, spares, or the 10th frame's special rules. Let's break down how to debug this:
First, Let's Pin Down the Likely Issues
Since you're getting 98 instead of the expected 96, your code is overcounting by 2 points. Here are the most probable culprits:
1. Incorrect Spare/Strike Bonus Calculation
- Spares: If your code is adding two subsequent rolls instead of one for a spare, that could add an extra 2 points (e.g., if the next roll is a 2).
- Strikes: If you're not stopping bonus calculations after the 10th frame, you might be counting the extra 10th-frame rolls twice (once as part of the strike bonus, once as a new frame).
2. Flawed String Parsing
Your rolls method cuts off at if (s..., so let's verify how you're handling characters:
- For a strike (
X): Are you storing only one10in therollsarray, and incrementingrollby 1? If you're incorrectly storing10and0(and incrementing by 2), this shifts all subsequent rolls and breaks bonus math. - For a spare (
/): Are you calculating the second roll as10 - previousDigit(e.g.,7/becomes7and3)? Storing10directly for the/would overcount the frame. - For a gutter ball (
-): Are you storing0instead of skipping the entry?
3. Not Limiting Calculations to 10 Frames
If your score calculation loop runs through the entire rolls array (21 entries) instead of stopping after 10 frames, you'll count the extra 10th-frame rolls (for strikes/spares) as an 11th frame. For example, if those extra rolls sum to 2, that's exactly your overcount.
Example Fix for Score Calculation
Here's a standard, correct score calculation method to compare against your code:
public int calculateScore() { int totalScore = 0; int currentRoll = 0; for (int frame = 0; frame < 10; frame++) { // Handle strike if (rolls[currentRoll] == 10) { totalScore += 10 + rolls[currentRoll + 1] + rolls[currentRoll + 2]; currentRoll++; // Strike only uses one roll } // Handle spare else if (rolls[currentRoll] + rolls[currentRoll + 1] == 10) { totalScore += 10 + rolls[currentRoll + 2]; currentRoll += 2; // Spare uses two rolls } // Open frame else { totalScore += rolls[currentRoll] + rolls[currentRoll + 1]; currentRoll += 2; } } return totalScore; }
Debugging Steps to Confirm
- Log the
rollsarray: Print out the values stored after parsing your test case's scorecard. Compare them to a manual parse of the same string—this will catch parsing errors immediately. - Step through the score calculation: Manually compute the score frame by frame, then walk through your code's logic to see where it deviates. Look for the frame where the total jumps by an extra 2 points.
- Verify the 10th frame: If your test case includes a strike or spare in the 10th frame, ensure the extra rolls are only counted as part of the 10th frame's bonus, not as a new frame.
内容的提问来源于stack exchange,提问作者Jon309

