Java替换特定字符 [英] Java replacement of specific characters
本文介绍了Java替换特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我在这个网站上的第一个问题,所以我会尽量不要成为一个完整的菜鸟..
This is my first question on this site so i'll try not to be a total noob..
我目前正在用java创建刽子手游戏。
所以我的问题是,如果给我们一个单词ghost
并且ghost被替换为_,
I'm currently creating hangman game in java. So my question to you is if we are given a word "ghost" and ghost is replaced with "_ ",
hiddenWord = ghost.length();
for (i=0; i < ghost.lenth(); i ++)
System.out.print("_ ")
给我们输出
_ _ _ _ _
假设我们猜猜字母O
猜到字母o,我如何替换`
Lets say we guess the letter "O" the letter "o" is guessed, how do i replace `
"_ _ _ _ _" 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语句使用三元运算符:
You can simplify the if statement using the ternary operator:
System.out.print(String.valueOf(ghost.charAt(i)).equalsIgnoreCase(input) ? input + " " : "_ ");
这篇关于Java替换特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文