1

I've replaced a string so that all the letters appear as **'s however when I ask the user for input of a char, I can't seem to get the letters to revert back from *'s into strings. I will show you below what I have done in my code:

    System.out.println(randomPirateWord.replaceAll("\\S", "*"));
    System.out.println("guess a letter");
    char letterGuesed = input.findInLine(".").charAt(0);
    System.out.println(randomPirateWord.replaceAll("\\S"+letterGuesed,"*")); 

3 Answers 3

1

Method replaceAll works in the opposite direction. First is a regular expression, and next the replacement for match, so you replace guessed letters with '*' and that's propably opposite to what you want to achieve.

Sign up to request clarification or add additional context in comments.

Comments

0

I would use a String that holds your hiddenWord, and in a different function just display the length of the string in *s, then compare the letterGuessed to hiddenWord and change the *s back to the hiddenWord that way.

Comments

0

Maybe not with replace all, but this seems to work:

import java.util.Scanner;
class hola{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String randomPirateWord = "HelloWorld";
        System.out.println("");
        boolean notComplete = true;
        char words[] = new char[randomPirateWord.length()];
        char words2[] = new char[randomPirateWord.length()];
        for(int i = 0; i < randomPirateWord.length(); i++){
            words[i] = randomPirateWord.charAt(i);
            words2[i] = '*';
        }
        while(notComplete){
            System.out.print("Type a letter: ");
            char letter = sc.next().charAt(0);
            notComplete = false;
            for(int i = 0; i < randomPirateWord.length(); i++){
                if(words[i] == letter){
                    words2[i] = letter;
                }
            }
            for(int i = 0; i < randomPirateWord.length(); i++){
                System.out.print(words2[i]);
            }
            for(int k = 0; k < randomPirateWord.length(); k++){
                if(words2[k] == '*'){
                    notComplete = true;
                    break;
                }
            }
            System.out.println("");
        }
    }
}

3 Comments

This works the best so far, the only problem is I need to be able to have a space in it and I need to be able to input another letter so that if the user was to input h it would display as hll **l
of course, that's made by your own... just read letter from user input as I said
the only exception is: "No spaces between words"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.