Java replacement of specific characters

前端 未结 4 895
北海茫月
北海茫月 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 18:49

    The easiest way to do that would be to use a Java regular expression on the target word. So whenever a user types in a letter you look for that letter in a regex match. That match will give you back the index of matching characters which you can then use to replace the letter in the __ version of the string.

    ...    
        listOfWords[9] = "zapping";
        Random generator = new Random();
        int lineNumber = generator.nextInt(9);
        disguisedWord = listOfWords[lineNumber];
        char[] hidden = disguisedWord.replaceAll("*","_").toCharArray();
    }
    
    public void makeGuess() throws IOException {
        System.out.println("Your word is " + disguisedWord.length() + " letters long.");
        System.out.println("Feel free to guess a letter.");
        String guess = System.in.read();
    
        Pattern pat = new Pattern(guess);
        Matcher mat = pat.matcher(disguisedWord);
        while (mat.find()) {
            int start = mat.start();
            hidden[start] = guess.toCharArray()[0];
        }
    }
    

提交回复
热议问题