import java.util.ArrayList; import java.util.List; /** * BowlingScores - An Example that might benefit from Pseudocode */ public class Bowling { public static final int kFramesPerGame = 10; static class Round { int firstBall = 0; int secondBall = 0; int total = 0; boolean strike = false; boolean spare = false; } /** * Calculates the cumulative frame scores given the scores * for a sequence of balls. * * @pre The number of scores is valid for one game. * @param A string representation of a sequence of blank-delimited integers * for the number of pins knocked down for every ball thrown in the game. * @return List of ten frame scores, in order. */ public static List calculate(String ballScores) { String tokens[] = (ballScores.replaceAll("\t", " ")).split(" " + "{1,}"); int numTokens = tokens.length; List output = new ArrayList(); Round[] rounds = new Round[numTokens]; for (int i = 0; i < rounds.length; i++) { rounds[i] = new Round(); } for (int i = 0, a = 0; a < numTokens; i++) { rounds[i].firstBall = Integer.parseInt(tokens[a++]); //GO THROUGH LIST, INPUTTING INTO ROUNDS //SPECIAL EXCEPTIONS FOR LAST SET if (i == kFramesPerGame-1) { if (rounds[i].firstBall == kFramesPerGame) { rounds[i].strike = true; rounds[i + 1].firstBall = Integer.parseInt(tokens[a++]); rounds[i + 1].secondBall = Integer.parseInt(tokens[a++]); } else { rounds[i].secondBall = Integer.parseInt(tokens[a++]); } } else if (rounds[i].firstBall == kFramesPerGame && i < kFramesPerGame-1) { rounds[i].strike = true; } else if (i < kFramesPerGame) { rounds[i].secondBall = Integer.parseInt(tokens[a++]); } rounds[i].total = rounds[i].firstBall + rounds[i].secondBall; if (!rounds[i].strike && rounds[i].total == kFramesPerGame && i <= kFramesPerGame-1) { rounds[i].spare = true; } } //CARRY SCORE OVER FOR STRIKES/SPARES for (int i = 0; i <= kFramesPerGame; i++) { if (rounds[i].spare && i < kFramesPerGame-1) { rounds[i].total += rounds[i + 1].firstBall; } else if (rounds[i].strike && i < kFramesPerGame-1) { if (!rounds[i + 1].strike) { rounds[i].total += rounds[i + 1].total; } else { rounds[i].total += rounds[i + 1].total + rounds[i + 2].firstBall; } } if (i == kFramesPerGame-1) { rounds[i].total += rounds[i + 1].firstBall + rounds[i + 1].secondBall; } if (i > 0) { rounds[i].total += rounds[i - 1].total; } } for (int i = 0; i < kFramesPerGame; i++) { output.add(new Integer(rounds[i].total)); } return output; } }