简体   繁体   English

破折号变成猜字母

[英]Having dashes change into guessed letters

my program currently takes a random word and turns into dashes based on how many letters are in the word. 我的程序当前使用一个随机单词,并根据单词中的字母数将其变为破折号。 I then determine if a letter guessed is in the word, but I was unable to figure out how to have the correctly guessed letter replace the dashes accordingly. 然后,我确定单词中是否包含猜中的字母,但是我无法弄清楚如何用正确猜中的字母相应地替换破折号。 I looked through possible solutions on the site, but was unable to have one work for my current code. 我在网站上浏览了可能的解决方案,但无法为当前代码完成一项工作。

Code: 码:

public String hiddenWord(){
     word = randomWord.getRandomWord();
     String dashes = word.replaceAll("[^ ]", " _ ");
     return dashes;
}

public String guessNotification(){
    if(word.indexOf(hv.keyChar)!=-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
        letterGuessed = "There is a " + hv.keyChar + " in the word";
    }
    else if(word.indexOf(hv.keyChar)==-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
        letterGuessed = "No " + hv.keyChar + " in the word";
        guesses++;
        System.out.println(guesses);

    }
    else{
        letterGuessed = "Not a valid letter";
    }
    return letterGuessed;
}

public void newGame() {
    hv.createNotification(this, size);  
    guesses = 0;
    System.out.println(word);
}
}

Comments are all correct. 评论都是正确的。 But you may want to see example code: Add an array of correct guesses: 但是您可能想要查看示例代码:添加正确的猜测数组:

char[] correct = new char[26];  // or more, depends on whether u use non ascii chars

Initialize the array with eg ' '. 用“”初始化数组。 Then replace the dashes: 然后替换破折号:

StringBuilder guessedPart = new StringBuilder;
for (int lc = 0; lc < word.lenght(); lc++) {
  for (char c : correct)
    if (word.indexOf(lc) = c) guessedPart.append(c);
  if (guessedPart.length() < lc) guessedPart.append('_');
String guessedWord = guessedPart.toString();

That should do. 那应该做。

Here is how the logic of how to replace the appropriate dash with the correct user guess might look 这是如何用正确的用户猜测替换适当的破折号的逻辑的外观

    public static String guessNotification(String word, char userGuess, StringBuilder dashes) {

        int guessedIndex = word.indexOf(userGuess);
        if (guessedIndex != -1 && (userGuess >= 'a' && userGuess <= 'z')) {

            letterGuessed = "There is a " + userGuess + " in the word";
            dashes.setCharAt(guessedIndex*3+1, userGuess);

        }

        else if (guessedIndex == -1 && (userGuess >= 'a' && userGuess <= 'z')) {

            letterGuessed = "No " + userGuess + " in the word";
            guesses++;

        }
        else {

            letterGuessed = "Not a valid letter";

        }

        return letterGuessed;

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM