Java Hangman - 错误检查

时间:2012-11-10 21:29:59

标签: java error-handling indexof

对于我的刽子手游戏,我想有一堆错误信息来检查输入的信件超过一个字母,猜两次相同的字母等等。到目前为止我的完整代码:

    import java.awt.Color;
    import java.awt.Font;
    import java.util.Random;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.FontUIResource;

    public class MainFrame extends javax.swing.JFrame {

        public MainFrame() {
            initComponents();
        }
        //declare variables
        static String secretWord = "";
        double result = 0;
        StringBuilder mainWord = new StringBuilder();
        StringBuilder xletters = new StringBuilder(); // letters guessed
        String[] words = {"technology", "computer", "camera", "graphic", "digital", "media", "technician",
            "photography", "troubleshoot", "pixels", "application", "download"};
        Random r = new Random();
        int randValue = r.nextInt(12);
        String guessWord = words[randValue];
        int errors = 0;
        public static int wins = 0, losses = 0;
        String foundWord = null;
        private void GuessButtonActionPerformed(java.awt.event.ActionEvent evt)         {                                            
            String strGuess = GuessText.getText(); //user input           
            String letter = strGuess;
            xletters.append(strGuess.toUpperCase());
            String GuessedLetters = xletters.toString();

            try {
    //replace underscores with letters as they are guessed
                do {
                    for (int i = 0; i < 1; i++) {
                        secretWord = secretWord + letter.charAt(0);
                        foundWord = words[randValue].replaceAll("[^" + secretWord + "]", "_ ");
                        //if user entered more than one letter
                        if (strGuess.length() > 1) {
                            JOptionPane.showMessageDialog(null, "Only one letter at a time!");
                            xletters.append("");
                            GuessedLetters = null;
                            GuessText.setText(null);
                            GuessText.requestFocusInWindow();
                        } //if letter isn't in word
                        else if (guessWord.indexOf(strGuess) == -1) {
                            JOptionPane.showMessageDialog(null, "Sorry, that wasn't in the word.");
                            errors++;
                            if (errors == 1) {
                                Hangman0.setVisible(false);
                            }
                            if (errors == 2) {
                                Hangman1.setVisible(false);
                            }
                            if (errors == 3) {
                                Hangman2.setVisible(false);
                            }
                            if (errors == 4) {
                                Hangman3.setVisible(false);
                            }
                            if (errors == 5) {
                                Hangman4.setVisible(false);
                            }
                            if (errors == 6) {
                                Hangman5.setVisible(false);
                            }
                            if (errors == 7) {
                                Hangman6.setVisible(false);
                            }
                            if (errors == 8) {
                                Hangman7.setVisible(false);
                            }
                            if (errors == 9) {
                                Hangman8.setVisible(false);
                            }
                            if (errors == 10) {
                                Hangman9.setVisible(false);
                                JOptionPane.showMessageDialog(null, "You lost! The word was: " + guessWord);
                                losses++;
                                DirectionsFrame DFrame = new DirectionsFrame();
                                DFrame.setVisible(true);
                                setVisible(false);
                                MainFrame MFrame = new MainFrame();
                                MFrame.dispose();
                                xletters.delete(0, 100);
                                secretWord = "";
                                foundWord = null;
                                strGuess = null;
                                String strLosses = Integer.toString(losses);
                                String strWin = Integer.toString(wins);
                                DirectionsFrame.WinsLabel.setText(strWin);
                                DirectionsFrame.LossesLabel.setText(strLosses);
                            }
                }
            }
                    WordLabel.setText(foundWord.toUpperCase());
                    GuessedLabel.setText(GuessedLetters);
                    GuessText.setText(null);
                    GuessText.requestFocusInWindow();
                } while (foundWord == null);
                if (foundWord.equalsIgnoreCase(guessWord)) {
                    JOptionPane.showMessageDialog(null, "Yay!");
                    wins++;
                    DirectionsFrame DFrame = new DirectionsFrame();
                    DFrame.setVisible(true);
                    setVisible(false);
                    MainFrame MFrame = new MainFrame();
                    MFrame.dispose();
                    xletters.delete(0, 100);
                    secretWord = "";
                    foundWord = null;
                    String strWin = Integer.toString(wins);
                    String strLosses = Integer.toString(losses);
                    DirectionsFrame.WinsLabel.setText(strWin);
                    DirectionsFrame.LossesLabel.setText(strLosses);
                }
            } catch (StringIndexOutOfBoundsException e) {
                JOptionPane.showMessageDialog(null, "Please enter a letter.");
                GuessedLabel.setText(GuessedLetters);
                GuessText.setText(null);
                GuessText.requestFocusInWindow();
            }
        }                                           


        private void GetButtonActionPerformed(java.awt.event.ActionEvent evt) {
            //print out underscores to begin game
            for (int i = 0; i < guessWord.length(); i++) {
                mainWord.append("_ ");
            }
            String SetMain = mainWord.toString();
            mainWord.append(secretWord);
            WordLabel.setText(SetMain);
            GuessButton.setEnabled(true);
            GetButton.setEnabled(false);
        }

我遇到的最麻烦的是检查用户是否两次输入相同的字母。所以你只能猜一次字母表中的一个字母。此外,它检查用户是否输入了多个字母的代码有一个我相信的错误,因为我希望它不会将这些字母添加到猜测的字母框中,它会添加。 (即用户猜测“hf”并且在猜到的字母中变成“hf”,它应该只是什么都没有)

我觉得答案在于方法indexOf(),但我不完全确定if条件会说什么......

我正在使用Netbeans IDE 7.2编译我的代码。请帮忙!感谢。

3 个答案:

答案 0 :(得分:1)

如果您想知道某件事是否已经被使用过,那么Set就会出现。例如,在刽子手游戏中使用的字母,你有Set<String>集合:

Set<String> lettersUsed = new HashSet<String>();

如果您想知道是否已经选择了某些内容:

String inputLetter = "Z";  // test for the letter Z

if (!lettersUsed.contains(inputLetter)) {
    lettersUsed.add(inputLetter);

    // process letter in word
} else {
    // letter has already been used!
}

如果您只想允许最初设置的特定字母集:

if (lettersAllowed.contains(inputLetter)) {
   lettersAllowed.remove(inputLetter);

   // process letter in word
} else {
   // letter is not allowed (anymore)
}

答案 1 :(得分:0)

为了看看他们是否已经猜到某些东西,你可以先得到一个空的String猜测,当他们猜测时,你可以将这个字母添加到字符串中:

String guesses = "";
...
guesses+= letter;

看起来你已经做了类似的事情,但一定要附加这封信,而不是为它创建一个新的字符串。这样,你可以每次检查你的猜测字符串是否已包含新猜测的字母(if(guesses.contains(letter))。

另外,我不确定你为什么只有一次迭代的for循环,但在多字母的情况下,你可以尝试突破循环,或继续,如果你

答案 2 :(得分:0)

我对你的信件检查的意思是:用旧信件制作一份清单。 每当玩家尝试写一封信时,如果该信件在您的列表中,则用for循环检查。 如果不是,则将其添加到列表中。 这是一个例子:

List<String> usedletters = new List<String>(26);

boolean checkLetterUsed(String input){
    boolean tempvariable = false;
    for(String letter: usedletters){
        if(letter==input){
            tempvariable = true;
        }
    }
    if(tempvariable){
        return true;
    }else{
        usedletters.add(input);
        return false;
    }
}