Reputation: 237
I'm busy with an test phase for my bigger application, Hangman. But before I can move on to that code, I have to first figure out this code.
Now, I've created 2 Strings: 1 that's the word, and 1 to hide that word in the same number of letters the original word contains but with '-'
. Now, someone gave me exactly the code I was looking for it reads the original string and the replaces the '-'
in the second string at he same position depending if the char is in the letter, now I've created a loop to loop six times but the word doesn't keep the previous letter guessed (if guessed correct)
import javax.swing.*;
public class MyThisTest{
public static void main(String[] args){
int error = 0;
while(error < 6){
char guessLetter = JOptionPane.showInputDialog(null, "Enter a letter:").charAt(0);
String original = "painting";
String secret = new String(new char[original.length()]).replace('\0', '-');
StringBuilder builder = new StringBuilder(secret);
for (int i = 0; i < original.length(); i++){
if (original.charAt(i) == guessLetter){
builder.setCharAt(i, guessLetter);
}
}
secret = builder.toString();
error++;
System.out.println(secret);
System.out.println(original);
}
}
}
Upvotes: 2
Views: 212
Reputation: 285405
A problem above is that you're creating your StringBuilder
inside of the while loop, so with each loop it gets re-created. The solution: Create your StringBuilder
and secret word before the while loop. This way the StringBuilder
gets created once and retains changes made in the loop.
Upvotes: 1
Reputation: 26386
Let's start with this
int error = 0;
String original = "painting";
String secret = new String(new char[original.length()]).replace('\0', '-');
while(error < 6)
{
char guessLetter = JOptionPane.showInputDialog(null, "Enter a letter:").charAt(0);
StringBuilder builder = new StringBuilder(secret);
for (int i = 0; i < original.length(); i++){
if (original.charAt(i) == guessLetter){
builder.setCharAt(i, guessLetter);
}
}
secret = builder.toString();
error++;
}
System.out.println(secret);
System.out.println(original);
Upvotes: 0
Reputation: 1
You need to change only 2 lines of code, put it before while
cycle
String original = "painting";
String secret = new String(new char[original.length()]).replace('\0', '-');
Upvotes: 1