java 特定字符,Java替换特定字符

这是我在本网站上的第一个问题,所以我将尽量避免成为一个新手.

我目前正在用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值