gpt4 book ai didi

Java替换特定字符

转载 作者:行者123 更新时间:2023-12-01 05:01:27 25 4
gpt4 key购买 nike

这是我在这个网站上的第一个问题,所以我会尽量不要成为一个十足的菜鸟..

我目前正在用java 创建刽子手游戏。所以我问你的问题是我们是否被赋予了“幽灵”这个词并将 Ghost 替换为“_”,

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替换特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13341581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com