Java的刽子手 - 替换为字符下划线 [英] Java Hangman - replacing underscore with character

查看:160
本文介绍了Java的刽子手 - 替换为字符下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创造了我的Java类刽子手游戏,但我有麻烦,用字母代替单词中的下划线。我把它打印出来的字像下划线:

So I'm creating a hangman game for my java class, but I'm having troubles replacing the underscores in the word with letters. I got it to print out the word in underscores like:

     for(int i = 0; i < GuessWord.length(); i++) { 
                if (guesses[GuessWord.charAt(i) - 'a']) { 
                    mainword.append(words[i].charAt(i));
                }
                else {
                    mainword.append("_");

                }
                mainword.append(" ");
            }

剩下的就是我的code的其余部分。我要提到我在NetBeans IDE的7.2工作,我使用的JLayeredPane显示所有的内容,而不是System.out.print。谢谢!

The rest is the rest of my code. I should mention I'm working in Netbeans IDE 7.2 and I'm using a JLayeredPane to display everything, not System.out.print. Thanks!

    import java.util.Random;
    import java.util.Scanner;
    import javax.swing.JOptionPane;

    public class MainFrame extends javax.swing.JFrame {

        public MainFrame() {
            initComponents();
        }

    //declare variables                      
    static String SecretWord = "";
    static String Letters = "";
    double Result = 0;
    String SetMain = null;
    StringBuilder mainword = new StringBuilder();
    StringBuilder gletters = new StringBuilder();
    boolean[] guesses = new boolean[26];
    String[] words = {"technology", "computer", "camera", "graphic design", "digital", "media", "technician", "photography", "troubleshoot", "pixels", "application", "download"};
    Random r = new Random();
    int randvalue = r.nextInt(11);
    String GuessWord = words[randvalue];


        private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
    mainword.append(SecretWord);
    //make word in underscore form
        for(int i = 0; i < GuessWord.length(); i++) { 
                if (guesses[GuessWord.charAt(i) - 'a']) { 
                    mainword.append(words[i].charAt(i));
                }
                else {
                    mainword.append("_");

                }
                mainword.append(" ");
            }

   //put in label
   SetMain = mainword.toString();
   WordLabel.setText(SetMain);
   GuessButton.setEnabled(true);
   GoButton.setEnabled(false);
}                           


private void GuessButtonActionPerformed(java.awt.event.ActionEvent evt) {                                      
    //declare variables      
    String strGuess = GuessText.getText();
    String SetMain = null;
    String GuessedLetters = null;
    Result = 1;//(int)(Math.random() * 11) + 1;
    int errors = 0;
    int i = 0;
    char guess2 = strGuess.charAt(i);
    gletters.append(Letters);

    //*******MAJOR PROBLEM AREA FOCUS HERE*******
    do{
        //replace underscore with guessed letter
        for(i = 0; i < GuessWord.length(); i++) { 
                if (GuessWord.charAt(i) == guess2) { 
                   mainword.replace(0,i,strGuess.toUpperCase()); 
                }
                else {
                    mainword.append("_");

                }
                mainword.append(" ");
            }

    //put in labels
    SetMain = mainword.toString();
    GuessedLetters = gletters.toString();
    WordLabel.setText(SetMain);
    GuessedLabel.setText(GuessedLetters);
    GuessText.setText(null);
    GuessText.requestFocusInWindow();
    }//end of do

while(SetMain == null);
if (SetMain.equalsIgnoreCase(GuessWord)){
    //show winning message to user and reset game
    JOptionPane.showMessageDialog(null, "Congrats!");
    GuessButton.setEnabled(false);
    GoButton.setEnabled(true);
    WordLabel.setText(null);
    GuessedLabel.setText(null);
    WinsLabel.setText("1");
}
//if too many errors show lost message
else if (errors >= 5){
    JOptionPane.showMessageDialog(null, "You Lost!");
    GuessButton.setEnabled(false);
    GoButton.setEnabled(true);
    WordLabel.setText(null);
    GuessedLabel.setText(null);
    LossesLabel.setText("1");
}
    }//end of 1GAME
}                                           

任何帮助将是巨大的!请没什么太复杂了。也标志着我在我的主要问题领域是在上面的code。

Any help would be great! Please nothing too complicated. Also I marked where my major problem area is in the above code.

推荐答案

我想尝试一个更简单的方法,在你认为你可以改变基于输入字符数组。这是观念的全部测试说明:

I'd try a simpler approach, in which you hold an array of characters that you can change based on an input. This is an overal description of the idea:

char guess[] = {'_', '_', '_', '_', '_', ' ', '_', '_', '_', '_', '_'};
// It's "Hello World" :)
if(input == answer.getCharAt(inputIndex))
    guess[inputIndex] = answer.getCharAt(inputIndex); 
    //replace the underscore with the correct character
else
    //Add it to a list of used characters, ignore it or do as you've been asked to    

在你的情况,创建该通过调用数组 answer.toCharArray(),其中答案是具有正确的单词串。你会想通过替换该字符串以下划线的所有字符的replaceAll([A-ZA-Z0-9],_)(只记得保持原来的答案太)。第一个参数是一个常规的前pression,意思是组中的所有字符从A到Z,从A到Z和0〜9,你需要检查一些的正防爆pressions 来习惯他们,相信我,你会使用它们比早更高版本。

In your case, create this guess array by invoking answer.toCharArray() where answer is the string that has the correct word. You'll want to replace all the characters in that string with underscores by using replaceAll("[A-Za-z0-9]", "_") (just remember to keep the original answer too). The first parameter is a regular expression that means "The group of All characters from A to Z, from a to z and from 0 to 9", you'll want to check up some Regular Expressions to get used to them, and trust me, you'll use them more sooner than later.

然后,你只是要替换猜[I] answer.getCharAt(我)每次一种猜测是正确完成,避免了人物建立一个字符串的字符的繁琐工作这可能会非常棘手。

Then, you'll just want to replace guess[i] with answer.getCharAt(i) everytime a guess is done correctly, avoiding the tedious work of building a string character by character which can be tricky.

这是一个不同的方法的简要说明,因为它是,如果你想尝试与否和普通的实施是由你,你可以决定一个assigment。我只是描述了一个主意。

This is a brief description of a different approach, since it's an assigment you can decide if you want to try it or not and the general implementation is up to you. I'll just describe an idea.

这篇关于Java的刽子手 - 替换为字符下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆