단어에서 특정 문자의 색인을 얻는 가장 좋은 방법은 무엇인지 알고 싶습니다. 내가 행맨 게임을 만들고 수정하기 때문에 내가 이것을하고있는 이유가있다. 나는 이미 게임을 끝내고 잘 작동하지만 점수 기반 시스템을 구현하려고합니다. 부울 값을 사용하여 답변이 맞는지 틀린지 확인하는 keepScore()라는 메서드를 만들었습니다. 맞다면 발견 된 각 편지에 대해 10 점을 더할 것입니다. 그것의 틀린 경우에, 나는 10 점을 공제 할 것이다. 내 메서드 keepScore()가 잘못 구현되었습니다?문자열 또는 문자 배열의 인덱스를 가져 오는 가장 좋은 방법은 무엇입니까?
Hangman.java 당신이 방법에 Game.java
package Game;
/* This class is responsible for implementing the game
* logic.
*/
public class Game {
//Declare our member variables
public final static int TOTAL_TRIES = 3;
public final static int MAX_SCORE_POINTS = 10;
private String mAnswer;
private String lettersHit;
private String lettersMissed;
private int score;
//Default constructor
public Game(String answer) {
//Initialize our member variables
mAnswer = answer.toLowerCase();
lettersHit = "";
lettersMissed = "";
}
//This method checks to see if the letter was a hit or a miss
public boolean checkLetter(char letter){
letter = validateGuess(letter);
boolean isHit = mAnswer.indexOf(letter) != -1;
//If correct
if (isHit) {
//Add the letter to the lettersHit pool
lettersHit += letter;
keepScore(isHit);
System.out.println("Hit! Score: " + score);
}else {
//Add the letter to the lettersMissed pool
lettersMissed += letter;
keepScore(isHit);
System.out.println("Missed! Score: " + score);
}
return isHit;
}
private void keepScore(boolean isHit) {
if(isHit) {
for (int i = 0; i < lettersHit.length(); i++) {
score += MAX_SCORE_POINTS;
}
} else {
for (int i = 0; i < lettersMissed.length(); i++) {
score -= MAX_SCORE_POINTS;
}
}
}
/*
This method handles an empty string input. For example,
if the user were to press enter on input a 0 length String
will cause the program to crash.
*/
public boolean checkLetter(String letters) {
if (letters.length() == 0) {
throw new IllegalArgumentException("No letter entered");
}
return checkLetter(letters.charAt(0));
}
//This method validates the user guess
private char validateGuess(char letter) {
//If the character is not a letter
if (!Character.isLetter(letter)) {
//Ask user for a valid letter
throw new IllegalArgumentException("A letter is required!");
}
//If entry was valid, convert character to lowercase
letter = Character.toLowerCase(letter);
//Check if the letter has been guessed already
if (lettersHit.indexOf(letter) != -1 || lettersMissed.indexOf(letter) != -1) {
throw new IllegalArgumentException("The letter " + letter + " has already been guessed");
}
return letter;
}
//This method keeps track of the user's game progress
public String getCurrentProgress() {
String progress = "";
//For each character in the array of strings of mAnswer
for (char letter : mAnswer.toCharArray()) {
char display = '-';
if (lettersHit.indexOf(letter) != -1){
display = letter;
}
progress += display;
}
return progress;
}
//Get the current remaining tries
public int getRemainingTries() {
return TOTAL_TRIES - lettersMissed.length();
}
//Get the current answer
public String getAnswer() {
return mAnswer;
}
//This method checks if the game is won.
public boolean isWon() {
return getCurrentProgress().indexOf('-') == -1;
}
public int getScore(){
return score;
}
}
Prompter.java
이package Prompter;
import Game.Game;
import java.util.Scanner;
/* This class is responsible for displaying instructions and information to the user
* regarding the game.
*/
public class Prompter {
//The game object
private Game mGame;
private boolean isHit;
private boolean acceptable;
//Default constructor
public Prompter(Game game) {
//Get the instance of our game
mGame = game;
isHit = false;
acceptable = false;
}
//This method prompts the user for a guess
public boolean promptForGuess() {
//Create an instance of scanner
Scanner scanner = new Scanner(System.in);
//Loop for input
do {
System.out.println("Please enter a letter: ");
String guess = scanner.nextLine();
try {
isHit = mGame.checkLetter(guess);
acceptable = true;
}catch (IllegalArgumentException iae) {
System.out.printf("%s. Please try again!%n", iae.getMessage());
}
} while (!acceptable);
return isHit;
}
//This method displays the progress
public void displayProgress() {
System.out.printf("You have %d tries to guess the answer" +
" before you are taken to the gallows. Try to solve: %s%n", mGame.getRemainingTries(),
mGame.getCurrentProgress());
}
//This method displays the outcome of the game
public void displayOutcome() {
if(mGame.isWon()) {
System.out.printf("Congratulations! you won with %d tries remaining.%n" +
"Your total score: %d%n", mGame.getRemainingTries(), mGame.getScore());
}else {
System.out.printf("Bummer! The answer was: %s", mGame.getAnswer());
}
}
}
이미 가장 좋은 방법을 사용하고 있습니다. String.indexOf(). 그래서 ** 실제 ** 질문은 무엇입니까? 디버거를 사용하여 코드를 한 줄씩 실행하고 변수 값을 검사 한 다음 코드에서 버그를 찾으셨습니까? –
'keepScore' 메소드가 잘못되었습니다 : 이미 스코어에있는 다른 글자 수를 10 * 더하거나 뺍니다. – Nathan
포인트의 양을 추적하기 위해 문자열의 길이를 사용하기 때문에 길이가 매번 증가하므로 10을 곱합니다. 문자열의 문자 색인을 얻고 싶습니다. 응답이 Nizeet 인 경우 나는 그것이 다음과 같이 될 것이라고 생각한다 : --- ee- 따라서 나의 포인트는 20이된다. 다음 추측, n : n - ee- 이제 나의 포인트는 30이다. 이것은 여기서 일어나지 않으며 추측의 인덱스는 항상 0, 항상 확실하게 첫 번째 추측은 0인지의 여부를 정확하게 계산합니다. –