获取String或Char数组索引的最佳方法是什么?

时间:2017-09-20 15:30:25

标签: java arrays string char string-length

我想知道获取单词中特定字母索引的最佳方法是什么。我这样做的原因是因为我正在制作和修改一个Hangman游戏。我已经完成了游戏,它运作良好,但我想实现一个基于分数的系统。我创建了一个名为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());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

看看你的这个方法:

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

它没有MAX_SCORE_POINTS次添加你刚刚找到的好信的数字,它会使用lettersHit中的好字母数量。现在,lettersHit中的内容是什么?好吧,从开始就有你发现的所有信件。

所以你有:

word to guess: anaconda

letter: a
lettersHit = "a", score += (lettersHit.length * 10) = 10
letter: c
lettersHit = "ac", score += (lettersHit.length * 10) = 30

您可以使用StringUtils.countMatches(mAnswer, letter);来获取出现次数,从而得分。