mardi 24 novembre 2015

Guess Number Game GUI - Infinite Loop

I'm making a guess the number program and I'm having trouble with my loop. When I run the program and input a number into the textfield and hit enter it freezes. I figured out that this might be happening because of an infinite loop. Feel free to correct me if I'm wrong. Basically when I enter a number into the textfield and press enter it suppose to change a label and change background color but this doesn't happen and I think its because my loop runs until win becomes true and when I type in my number it keeps running that number instead of outputting the correct label and letting me input a different number into the textfield.

public void actionPerformed(ActionEvent event) 
{        
    boolean win = false;
    guess = Integer.parseInt(guessText.getText());

    while (win == false)
    {
        numOfTries++;

        if ( guess == numToGuess)
        {
            win = true;
        }
        else if ( guess < numToGuess)
        {
            winLbl.setText("Too Low");
            guessPanel.setBackground(Color.red);
        }
        else if ( guess > numToGuess)
        {
            winLbl.setText("Too High");
            guessPanel.setBackground(Color.blue);
        }
    }
    winLbl.setText("Correct! It took you " + numOfTries + " tries to win.");
    guessPanel.setBackground(Color.green);
}  




Aucun commentaire:

Enregistrer un commentaire