【问题标题】:Hangman Java - Replacing UnderscoresHangman Java - 替换下划线
【发布时间】:2016-01-15 22:31:36
【问题描述】:

我的刽子手游戏快完成了,但我无法用这些字母替换正确猜到的字母的下划线。每当我选择正确的字母时,都会创建一个无限循环。非常感谢任何帮助。

//公共字符串短语;

//公共字符串newMask;

public boolean showLetter(String letter)
{
    phrase = phrase.toUpperCase();

    int pos = phrase.indexOf(letter);
    if(pos != -1) { //If the letter is part of the phrase.
        do {
            //Letter and phrase don't change.
            //Cut the "a" 

            pos = phrase.indexOf(letter);
            //Make a new string and take the digit out. 
            //I must break out of the loop.
            //add code here 

            newMask = phrase.substring(0,pos)+phrase.charAt(pos)+phrase.substring(pos);

        } while (pos != -1);
        setValue(mask);
    } else {
        return false;
    }
    return true;
}

【问题讨论】:

  • 为什么它不会创建无限循环??? letter 在循环内总是相同的。因此pos 不会改变。那么控制将如何从循环中出来?不明白循环有什么用?
  • 循环的使用是用正确的字母替换所有必要的下划线。例如,因为字母是“All's well that ends well!”,如果我选择“e”,则所有代表“e”的下划线都更改为 e。你知道我该怎么做吗?
  • 你不能使用String replace() 方法吗?
  • 看看String#indexOf(int, int)。您需要从最后找到的索引 + 1 开始,否则您只是一遍又一遍地重复相同的操作。此外,newMask = ... 行当前将整个掩码替换为 phrase(一个字母加倍),这可能不是您想要的。
  • 这里为什么需要做while循环?如果你想循环然后在函数showLetter(String letter)上做

标签: java replace


【解决方案1】:

嘿,tommy,当你输入字母时,我做了类似的方法,它会检查它是否在短语 String 中,如果它在其中,它将返回 true,并打印出新的掩码。

static String phrase = "Word";
static String mask = "_ _ _ _";
public  boolean showLetter(String letter)
{       
    phrase = phrase.toUpperCase();
    for(int v  =0; v < phrase.length();v++){
        if(phrase.charAt(v) == letter.toUpperCase().charAt(0)){                
            String newMask = "";
            mask =mask.replace(" ", "");
            for(int vv = 0;vv < mask.length(); vv++){                    
                if(vv == v){
                    newMask = newMask +  letter.charAt(0) + " " ;
                }else if (mask.charAt(vv) != '_'){
                    newMask = newMask +mask.charAt(vv) + " ";
                }else{
                    newMask = newMask + "_ ";
                }
            }
            mask = newMask;
            return true;
        }            
    }
    return false;
}

输入:“w”

输出:真,“w _ _ _”

如果您不想打印输出,请将“//”放在 System.out.println(mask); 前面;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多