Search code examples
javaswingdialogjoptionpane

While loop loops everything but doesn't save


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);
    }

}
}

Solution

  • 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', '-');