0

I want to store the questionmarks in a string because later I will be using string replace method to replace those question marks with a character the user guess. This is kind of a hangman game.

Scanner keyboard = new Scanner(System.in);
    int length;
    String originalString;
    String option= "abcdefghijklmnopqrstuvwxyz";
    String questionmarks;

    System.out.println("Please enter a string");
    originalString=keyboard.nextLine();
    System.out.println(originalString);

    length=originalString.length();
    for(int i=1; i<=length;i++){
        System.out.print("?");
    }




}
5
  • 2
    You have not provided a problem statement. Commented Aug 1, 2013 at 14:38
  • Do you want as much number of ? as the length of the string? Commented Aug 1, 2013 at 14:39
  • yes, that what the loop does. Prints out ? of length of the string. Commented Aug 1, 2013 at 14:39
  • 1
    is this all you want to do ?=> for(int i=1; i<=length;i++){ questionmarks += "?"; } Commented Aug 1, 2013 at 14:40
  • The question is once i get the question marks, i want to store them into a string Commented Aug 1, 2013 at 14:41

1 Answer 1

2

What about

questionmarks = originalString.replaceAll(".", "?");

i.e. replace every character (.) with a ?. This eliminates the need for an explicit for-loop.


For example:

String originalString = "abcd";
String questionmarks = originalString.replaceAll(".", "?");

System.out.println(questionmarks);
????
Sign up to request clarification or add additional context in comments.

2 Comments

In case anyone is horribly confused why replacing periods actually replaces letters, replaceAll uses regex.
Yeah i will accept the answer once the time is up, pretty straight answer. I didn't do this because we never learned this method in class. :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.