有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hangman屏蔽字符串,取消隐藏字符

我正在编写一个hangman应用程序,我必须编写代码,用“-”隐藏字符串中的每个字符(正在猜测的单词)。。。我在hoe上发布了很多问题,其中一个回答是:Hangman - hide String and then unhide each char if guessed correct

public class HangmanWord {

private static final char HIDECHAR = '_';

private String original;     
private String hidden;  

public HangmanWord(String original) {
    this.original = original;
    this.hidden = this.createHidden();
}

private String createHidden() {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < this.original.length; i++) {
        sb.append(HIDECHAR);
    }
    return sb.toString();
}

public boolean check(char input) {
    boolean found = false;
    for (int i = 0; i < this.original.length; i++) {
        if (this.original[i].equals(input)) {
            found = true;
            this.hidden[i] = this.original[i];
        }
    }
    return found;
}

//getter and setter
}

public class TestClass() {

public static void main(String[] args) {
    String secret = "stackoverflow";
    int wrongGuesses = 0;
    HangmanWord hngm = new HangmanWord(secret);
    System.out.println(hngm.getHidden()); // _____________
    if (hngm.check('a')) {
        System.out.println(hngm.getHidden()); // __a_________
    }
    else {
       wrongGuesses++;
    }
    //... and so on...
}
}

我试着用我的代码,我有很多错误和结论,它与我的代码不工作。在我的代码中,我创建了一个数组按钮,如果一个人点击一个按钮,我会收到一条消息,告诉他字母是否在单词中。。。现在我想替换这个代码,它不给我消息,但取消隐藏字符,如果没有字符,它必须更改图像

如果可能的话,有人能解释为什么我的代码不能使用它,或者有人能向我解释怎么做

我的按钮阵列:

public JButton getButton(final String text){
   final JButton button = new JButton(text);
    button.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
             if(original.toUpperCase().indexOf(button.getText())!=-1){
                 JOptionPane.showMessageDialog(null, "Your word does contain " + text       );
             }
             else{
                 JOptionPane.showMessageDialog(null, "There is no " + text );
                 error++;
                    if(error >= 0) imageName = "hangman1.jpg";
                    if(error >= 1) imageName = "hangman2.jpg";
                    if(error >= 2) imageName = "hangman3.jpg";
                    if(error >= 3) imageName = "hangman4.jpg";
                    if(error >= 4) imageName = "hangman5.jpg";
                    if(error >= 5) imageName = "hangman6.jpg";
                    if(error >= 7) imageName = "hangman7.jpg"; 
             }
             }
             });
             return button;
}

我的完整代码:

import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;

public final class Hangman extends JFrame implements ActionListener{
String original = readWord();
int error;
String imageName;

JButton btnAddWord = new JButton("Add New Word");
JButton btnRestart = new JButton("Restart");
JButton btnHelp = new JButton("Help");
JButton btnExit = new JButton("Exit");

JLabel word = new JLabel(original);

static JPanel panel1 = new JPanel();
static JPanel panel2 = new JPanel();
static JPanel panel3 = new JPanel();
static JPanel panel4 = new JPanel();

public Hangman(){
    Container content =getContentPane();
    content.setLayout(new GridLayout(0,1));

   btnAddWord.addActionListener(this);
   btnRestart.addActionListener(this);
   btnHelp.addActionListener(this);
   btnExit.addActionListener(this);

   ImageIcon icon = null;
   if(imageName != null){
   icon = new ImageIcon(imageName);
                    }
  JLabel image = new JLabel();
  image.setIcon(icon);
  panel2.add(image);

   panel3.add(word);
   panel4.add(btnAddWord);
   panel4.add(btnRestart);
   panel4.add(btnHelp);
   panel4.add(btnExit);

    for(char i = 'A'; i <= 'Z'; i++){
        String buttonText = new Character(i).toString();
        JButton button = getButton(buttonText);
        panel1.add(button);
    }
}

public JButton getButton(final String text){
   final JButton button = new JButton(text);
    button.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
             if(original.toUpperCase().indexOf(button.getText())!=-1){
                 JOptionPane.showMessageDialog(null, "Your word does contain " + text     );
             }
             else{
                 JOptionPane.showMessageDialog(null, "There is no " + text );
                 error++;
                    if(error >= 0) imageName = "hangman1.jpg";
                    if(error >= 1) imageName = "hangman2.jpg";
                    if(error >= 2) imageName = "hangman3.jpg";
                    if(error >= 3) imageName = "hangman4.jpg";
                    if(error >= 4) imageName = "hangman5.jpg";
                    if(error >= 5) imageName = "hangman6.jpg";
                    if(error >= 7) imageName = "hangman7.jpg"; 
             }
             }
             });
             return button;
}
public String readWord(){
    try{
        BufferedReader reader = new BufferedReader(new FileReader("Words.txt"));
        String line = reader.readLine();
        List<String> words = new ArrayList<String>();
        while(line != null){
            String[] wordsLine = line.split(" ");
            boolean addAll = words.addAll(Arrays.asList(wordsLine));
            line = reader.readLine();
        }
        Random rand = new Random(System.currentTimeMillis());
        String randomWord = words.get(rand.nextInt(words.size()));
        return randomWord;

}catch (Exception e){
    return null;
}
}
public void actionPerformed(ActionEvent e){
    if(e.getSource() == btnAddWord){
        try{
            FileWriter fw = new FileWriter("Words.txt", true);
            PrintWriter pw = new PrintWriter(fw, true);

            String word = JOptionPane.showInputDialog("Please enter a word: ");

            pw.println(word);
            pw.close();
        }
        catch(IOException ie){
            System.out.println("Error Thrown" + ie.getMessage());
        }
    }
    if(e.getSource() == btnRestart){

    }
    if(e.getSource() == btnHelp){
        String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word."
               + "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions."
               + "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark."
               + "\n"
               + "\nThe game is over when:"
               + "\nThe guessing player completes the word, or guesses the whole word correctly"
               + "\nThe other player completes the diagram";
       JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE);
    }
    if(e.getSource() == btnExit){
        System.exit(0);
    }
}

public static void main (String [] args){
    Hangman frame = new Hangman();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 600);
    frame.add(panel1, BorderLayout.NORTH);
    frame.add(panel2, BorderLayout.CENTER);
    frame.add(panel3, BorderLayout.SOUTH);
    frame.add(panel4, BorderLayout.SOUTH);
}
}

共 (2) 个答案

  1. # 1 楼答案

    您的代码已经有了一个很好的开端,但首先需要在编写代码之前将设计清晰地记在心里。让我们分步骤思考一下:

    • 启动应用程序时,加载文件中的所有单词。这是一个只执行一次的步骤,其结果(文件中的单词)应该被保存
    • 上一步似乎与GUI代码无关,因此您可能希望在main方法中执行,然后将结果传递给GUI类。您甚至可以将此功能提取到单独的类中,同时选择一个随机单词
    • 显示GUI后,您将显示一个表示隐藏单词的标签。此标签的文本应包含与单词字符相同数量的隐藏字符('-'
    • 每当按下正确的按钮时,应显示单词中所有匹配的字符
    • 每当按下错误的按钮时,错误计数器将递增,并显示图像
    • 当整个单词被揭开时,字符按钮应该被禁用

    这导致了一种设计,在这种设计中,您有一个单独的helper类,其中一个方法用于读取单词文件,另一个方法用于选择随机单词。可能是这样的:

    class WordsReader {
        public String[] readWords(String filename) {
            // ...
        }
    
        public String chooseWord(String[] words) {
            // ...
        }
    }
    

    选择新词后,应更新标签。这就是上面建议的HangmanWord类派上用场的地方。它存储原始单词及其隐藏的表示形式。这允许您在按钮的处理程序中调用check方法,并使用更新的隐藏表示更新标签的文本。剩下的代码应该可以很好地工作,尽管它仍然可以改进

  2. # 2 楼答案

    您可以获取字符串的字符,并在新字符串中用“-”替换猜测的字母,并显示该字符(而在幕后,您仍然拥有完整的字符)

    public [static] String hideString(String string, int[] guessedLetterIndices) {
        char[] chars = string.toCharArray();
        for(int index : guessedLetterIndices)
            chars[i] = '-';//Replace this with any letter
        for(int i = 0; i < chars.length; i++) {
            char c = '-';
            for(int index : guessedLetterIndices)
                if(index == i)
                    c = chars[i];
            chars[i] = c;
        }
    
        return new String(chars);
    }
    

    或者,如果您当前有一个他们选择的字符数组,而不是字符索引

    public [static] String hideString(String string, char[] guessedLetters) {
        char[] chars = string.toCharArray();
        char[] hidden = (string.replaceAll("(.|\n)", "-").toCharArray();
        for(int i=0;i<chars.length;i++) {
            for(char c : guessedLetters)
                if(chars[i] == c) {
                    hidden[i] = chars[i];
                    break;
                }
        ]
        return new String(chars);
    }
    

    那就是我要做的。至于为什么你的不起作用,你能告诉我你的错误吗?确保您正在导入StringBuilder和其他内容(无论它们使用什么)