Java replacement of specific characters

前端 未结 4 937
北海茫月
北海茫月 2021-01-23 18:32

This is my first question on this site so i\'ll try not to be a total noob..

I\'m currently creating hangman game in java. So my question to you is if we are given a wor

4条回答
  •  感动是毒
    2021-01-23 19:06

    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("_ ");
        }
    }
    

    You can simplify the if statement using the ternary operator:

    System.out.print(String.valueOf(ghost.charAt(i)).equalsIgnoreCase(input) ? input + " " : "_ ");
    

提交回复
热议问题