Search code examples
javaeventsjtextfield

How to extract information from a textfield and compare it to the previous input


I'm in an entry level java class and have to design a program that has the user guess a random number between 1-1000. I know that I need a separate class to extract the information from the textfield, but how can i store each successive guess? I need to state "Warmer" or "Colder" if the guess is closer or further away than the previous attempt.

private class Event implements ActionListener{
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == guessAgain)
        {

        }
        else if(e.getSource() == newGame)
        {

        }
        else if(e.getSource() == userGuess)
        {
            input = userGuess.getText();
            guess = Double.parseDouble(input);
        }

Solution

  • As per my comment:

    • Give your class an int field, previousGuess, and have it hold the previous guess.
    • When the button is pressed, get the input, convert it to an int and put it into an int local variable, say called currentGuess.
    • You might want a boolean field as well, firstGuess, that is initially true, so you know when there is no previous guess. Set this to false after checking if it is true or false and re-set it to true if you re-start the game.
    • Simply compare the previousGuess with the currentGuess and with the solution number and based on these comparisons present the appropriate output to the user.
    • Then assign currentGuess to previousGuess for the next go-around. i.e., previousGuess = currentGuess;

    That's it.


    Edit
    per DSlomer64's comment:

    To determine whether to say "warmer" or "colder", use Math.abs(), the absolute value function to hold previous and current amount of miss.