gpt4 book ai didi

java - For Loop 保龄球得分

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:19:55 24 4
gpt4 key购买 nike

我正在开展一个潜在实习项目,以获取保龄球分数的字符串输入并将它们相加为最终分数。我很难通过我的一项测试,想知道你是否可以帮助我找出我的错误。

无效的测试是 isNinetySix,它给我的结果是 98。请帮忙!

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] + ", ");
}
}
}

测试

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));
}
}

最佳答案

这里的问题似乎是您的 isSpare() 函数永远不会返回 true,因为您为每个 / 分配了一个值 10。将两个卷添加到一个帧中的结果是一个备用超过 10。如果我是你,我会尝试将 / 的分配清理为实际上是 10 - prev_role_score。这比让 isSpare() 检查是否大于 10 更干净。还有其他方法可以清理代码,您可以尝试重构一些代码来打动您提交给谁。

} else if (scoreCard.charAt(i) == '/') {
int diff = 10 - rolls[roll - 1];
rolls[roll++] = diff;
}

关于java - For Loop 保龄球得分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50144379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com