Search code examples
javainputwhile-loopterminallanterna

lanterna terminal input keeps repeating


I 'm making a simple java text-based hangman with lanterna (mainly becouse of clearscreen and user input in a console).

I have a problem with my user input: Once I typed in my input and run it trough my code, it keeps using that same input every time again, I can't insert another input anymore.

here's my code:

while (hidenWord.equals(word) == false) {
        //start of basic visual setup
        terminal.moveCursor(0,0);
        cursorPlace[0] = 0;cursorPlace[1] = 0;
        normalSetup(hidenWord, kansen, choose[categorie]);
        terminal.moveCursor(12, cursorPlace[1] - 3);
        //end of basic visual setup
        while (bool == false) {
            Thread.sleep(5);
            Key key = terminal.readInput();
            try {
                if (key.getKind() == Key.Kind.NormalKey) {
                    guess = (key).toString().substring(key.toString().lastIndexOf(' '));
                    terminal.putCharacter(key.getCharacter());
                }
            } catch (Exception err) {
            }
            try {
                if (key.getKind() == Key.Kind.Backspace) {
                    terminal.clearScreen();
                    terminal.moveCursor(0, 0);
                    cursorPlace[0] = 0;
                    cursorPlace[1] = 0;
                    normalSetup(hidenWord, kansen, choose[categorie]);
                    terminal.moveCursor(12, cursorPlace[1] - 3);
                }
            } catch (Exception err) {
            }
            try {
                if (key.getKind() == Key.Kind.Enter && guess != null) {
                    bool = true;
                }
            } catch (Exception err) {
            }
        }
        if(word.contains(guess)){
            guesses.add(guess);
            hidenWord = addHidden(guess, word);
        }else{
            kansen --;
            miss.add(guess);
        }
        //end of other visual objects
    }

thanks!


Solution

  • while (hidenWord.equals(word) == false) {
        // ...
    
        while (bool == false) {
            // ...
    
            try {
                if (key.getKind() == Key.Kind.Enter && guess != null) {
                    bool = true;
                }
    

    You set bool to true the first time you see an "Enter", and afterwards you never reset it back to false. As such, in the next iteration of the outer while loop, bool is true, so the inner while loop is not entered again.

    It would be simpler and better without using bool at all:

        while (true) {
            // ...
    
            try {
                if (key.getKind() == Key.Kind.Enter && guess != null) {
                    break;
                }