I'm working on a project for a potential internship to take a String input of bowling scores and add them up to a final score. I'm having difficult passing one of my tests and was wondering if you could help me figure out my fault.
The test that is not working is isNinetySix and it is giving me a result of 98 instead. Please help!
public class Game {
private int roll = 0;
private int[] rolls = new int[21];
public void rolls(String scoreCard) {
for (int i=0; i< scoreCard.length(); i++) {
if (scoreCard.charAt(i) == 'X') {
rolls[roll++] = 10;
} else if (scoreCard.charAt(i) == '/') {
rolls[roll++] = 10;
} else if (scoreCard.charAt(i) == '-') {
} else {
int x = scoreCard.charAt(i);
rolls[roll++] = x - '0';
}
}
}
public int score() {
int score = 0;
int cursor = 0;
for (int frame = 0; frame < 10; frame++) {
if (isStrike(cursor)) {
score += 10 + rolls[cursor+1] + rolls[cursor+2];
cursor ++;
} else if (isSpare(cursor)) {
score += 10 + rolls[cursor+2];
cursor += 2;
} else {
score += rolls[cursor] + rolls[cursor+1];
cursor += 2;
}
}
return score;
}
private boolean isStrike(int cursor) {
return rolls[cursor] == 10;
}
private boolean isSpare(int cursor) {
return rolls[cursor] + rolls[cursor+1] == 10;
}
//Print scores for each frame
public void printFrameScore(int[] frame) {
for (int i = 1; i < frame.length; i++) {
System.out.println(i + ": " + frame[i]);
}
}
public void displayRolls() {
for (int i = 0; i < rolls.length; i++) {
System.out.print(rolls[i] + ", ");
}
}
}
Tests
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import org.junit.Before;
import org.junit.Test;
public class GameTest {
private Game game;
@Before
public void setUp(){
game = new Game();
}
@Test
public void isPerfect() {
game.rolls("X-X-X-X-X-X-X-X-X-X-XX");
assertThat(game.score(), is(300));
}
@Test
public void isGutter() {
game.rolls("00-00-00-00-00-00-00-00-00-00");
assertThat(game.score(), is(0));
}
@Test
public void isNinety() {
game.rolls("45-54-36-27-09-63-81-18-90-72");
assertThat(game.score(), is(90));
}
@Test
public void isOneFifty(){
game.rolls("5/-5/-5/-5/-5/-5/-5/-5/-5/-5/-5");
assertThat(game.score(), is(150));
}
@Test
public void isNinetySix() {
game.rolls("45-54-36-27-09-63-81-18-90-7/-5");
assertThat(game.score(), is(96));
}
}
The problem here seems to be that your isSpare() function never returns true because you assigned each /
a value of 10. The result of the addition of the two rolls in a frame with a spare was more than 10. If I were you I would try to clean up the assignment of /
to actually be 10 - prev_role_score
. This would be cleaner than making isSpare() check for greater than 10. There are other ways to clean up the code to, you could try to refactor some to impress whoever you submit to.
} else if (scoreCard.charAt(i) == '/') {
int diff = 10 - rolls[roll - 1];
rolls[roll++] = diff;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With