这是我在本网站上的第一个问题,所以我将尽量避免成为一个新手.
我目前正在用Java创建子手游戏.
因此,我要问的是,是否给我们一个“鬼”的字眼
并将幽灵替换为“ _”,
hiddenWord = ghost.length();
for (i=0; i < ghost.lenth(); i ++)
System.out.print("_ ")
给我们输出
“ _ _ _ _ _”
可以说我们猜字母“ O”
字母“ o”被猜中,我该如何替换`
"_ _ _ _ _" with
"_ _ o _ _ "
我当前的班级文件
public void pickWord()
{
String[] listOfWords;
listOfWords = new String[10];
listOfWords[0] = "shenanigans";
listOfWords[1] = "conversely";
listOfWords[2] = "octopus";
listOfWords[3] = "dizzy";
listOfWords[4] = "malicious";
listOfWords[5] = "goosebumps";
listOfWords[6] = "flying";
listOfWords[7] = "staff";
listOfWords[8] = "xylophone";
listOfWords[9] = "zapping";
Random generator = new Random();
int lineNumber = generator.nextInt(9);
disguisedWord = listOfWords[lineNumber];
}
public void displayMark()
{
for( int i = 0; i < disguisedWord.length(); i ++)
underscore = underscore + "_ ";
System.out.println(underscore);
}
public void makeGuess() throws IOException
{
System.out.println("Your word is " + disguisedWord.length() + " letters long.");
System.out.println("Feel free to guess a letter.");
guess = (char)System.in.read();
解决方法:
String ghost = "ghost";
String input = "o";
for (int i = 0; i < ghost.length(); i++) {
if (String.valueOf(ghost.charAt(i)).equalsIgnoreCase(input)) {
System.out.print(input + " ");
} else {
System.out.print("_ ");
}
}
您可以使用三元运算符简化if语句:
System.out.print(String.valueOf(ghost.charAt(i)).equalsIgnoreCase(input) ? input + " " : "_ ");
标签:java,string,replace
来源: https://codeday.me/bug/20191013/1909341.html