lots of exercises in java... from https://github.com/exercism/java

BowlingGame.java 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class BowlingGame {
  4. private static final int NUMBER_OF_FRAMES = 10;
  5. private static final int MAXIMUM_FRAME_SCORE = 10;
  6. private List<Integer> rolls = new ArrayList<Integer>();
  7. public void roll(int pins) {
  8. rolls.add(pins);
  9. }
  10. public int score() {
  11. int score = 0;
  12. int frameIndex = 0;
  13. for (int i = 1; i <= NUMBER_OF_FRAMES; i++) {
  14. if (rolls.size() <= frameIndex) {
  15. throw new IllegalStateException("Score cannot be taken until the end of the game");
  16. }
  17. if (isStrike(frameIndex)) {
  18. if (rolls.size() <= frameIndex + 2) {
  19. throw new IllegalStateException("Score cannot be taken until the end of the game");
  20. }
  21. int strikeBonus = strikeBonus(frameIndex);
  22. if (strikeBonus > MAXIMUM_FRAME_SCORE && !isStrike(frameIndex + 1)) {
  23. throw new IllegalStateException("Pin count exceeds pins on the lane");
  24. }
  25. score += 10 + strikeBonus;
  26. frameIndex += i == NUMBER_OF_FRAMES ? 3 : 1;
  27. } else if (isSpare(frameIndex)) {
  28. if (rolls.size() <= frameIndex + 2) {
  29. throw new IllegalStateException("Score cannot be taken until the end of the game");
  30. }
  31. score += 10 + spareBonus(frameIndex);
  32. frameIndex += i == NUMBER_OF_FRAMES ? 3 : 2;
  33. } else {
  34. int frameScore = frameScore(frameIndex);
  35. if (frameScore < 0) {
  36. throw new IllegalStateException("Negative roll is invalid");
  37. } else if (frameScore > 10) {
  38. throw new IllegalStateException("Pin count exceeds pins on the lane");
  39. }
  40. score += frameScore;
  41. frameIndex += 2;
  42. }
  43. }
  44. if (!correctNumberOfRolls(frameIndex)) {
  45. throw new IllegalStateException("Cannot roll after game is over");
  46. }
  47. return score;
  48. }
  49. private boolean correctNumberOfRolls(int frameIndex) {
  50. return frameIndex == rolls.size();
  51. }
  52. private boolean isStrike(int frameIndex) {
  53. return rolls.get(frameIndex) == MAXIMUM_FRAME_SCORE;
  54. }
  55. private boolean isSpare(int frameIndex) {
  56. return rolls.get(frameIndex) + rolls.get(frameIndex + 1) == MAXIMUM_FRAME_SCORE;
  57. }
  58. private int strikeBonus(int frameIndex) {
  59. return rolls.get(frameIndex + 1) + rolls.get(frameIndex + 2);
  60. }
  61. private int spareBonus(int frameIndex) {
  62. return rolls.get(frameIndex + 2);
  63. }
  64. private int frameScore(int frameIndex) {
  65. return rolls.get(frameIndex) + rolls.get(frameIndex + 1);
  66. }
  67. }