単語内の特定の文字のインデックスを取得する最も良い方法は何ですか。私がこれをやっているのは、私がハングマンのゲームを作って修正しているからです。私はすでにゲームを終えていて、それはうまくいくが、スコアベースのシステムを実装したい。私は、答えが正しいかどうかを調べるためにboolean値をとるkeepScore()というメソッドを作成しました。それが正しい場合は、見つかった各文字に対して10ポイントを追加します。それが間違っていると、私は10ポイントを差し引います。私のメソッドkeepScore()は、間違ってどのようなヘルプが実装されていますか?文字列または文字配列のインデックスを取得する最も良い方法は何ですか?
Hangman.java
import Game.Game;
import Prompter.Prompter;
/* This class is the main class that starts the game.
* It instantiates the Game and Prompter objects.
*/
public class Hangman {
public static void main(String[] args) {
//Check if an argument has been passed, we expect the answer to be passed
if(args.length == 0) {
System.out.println("Expected: Java Hangman <answer>");
System.err.println("Answer is required!");
System.exit(1);
}
System.out.println("Welcome to Hangman!");
//Create an instance of our game
Game game = new Game(args[0]);
//Create an instance of our prompter
Prompter prompter = new Prompter(game);
//Starts the game
while (game.getRemainingTries() > 0 && !game.isWon()) {
prompter.displayProgress();
prompter.promptForGuess();
}
//Displays the outcome of the game
prompter.displayOutcome();
}
}
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()。あなたの**実際の**質問は何ですか?デバッガを使ってコードを1行ずつ実行し、変数の値を調べ、コード内のバグを見つけましたか? –
あなたの 'keepScore'メソッドは間違っています:スコアにすでに見つかっている別の文字の数を10 *追加/削除します。 – Nathan
私はポイントの量を追跡するために文字列の長さを使用しているので、長さは毎回増えて10で乗算されます。文字列の文字のインデックスを取得したいので、答えがNizeetそして私はそれが次のようになると思います:--- ee-したがって、私のポイントは20になります。次の推測、n:n - ee-今私のポイントは30です。これはここでは起こりません。 0、それは常に確かに最初の推測を正しくまたは間違って0として計算されます。 –