0

I've been trying to create a Hangman game in Java, and I have a string that looks like "_____" for a certain number of letters that they are supposed to represent. How would I replace just one of those, rather than all? I've heard that you can't replace an underscore with the String.replace method, but I couldn't figure it out with Pattern and Matcher. Here's the code:

String b = "____";
char c = b.charAt(0); 
b = b.replace(c, 'a');
System.out.println(b);

Please respond as soon as you can! Thanks!

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by hfx642
0

what you are doing here is copying a character from b into c and then playing with that c. What you should do instead is use substrings:

String b = "_____";
b = b.substring(0,3) + 'a' + b.substring(5);
System.out.println(b);

This should do it. You can modify the substring start and end index according to the program requirements.

2

You have two strings which are both the same length.
One with the underscores. And one with your word.
Search the second string to find the index of occurance of the letter.
The letter "a" is at index 2. (zero based, of course)

String Unders = "_____";
String Word  = "board";
int Index = Word.indexOf ("a");
Unders = Unders.substring (0, Index) + Word.substring (Index, Index + 1) + Unders.substring (Index + 1);

Your result would be "__a__"
Loop for each letter entered until no underscores are left.

Edited by hfx642: n/a

Votes + Comments
Nice
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.