简体   繁体   中英

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

Something along these lines for the "colder"/"warmer" issue...

public static void main(String[] args) {

  int guess, prevGuess, prevMiss, miss, secretNumber;

  secretNumber = 99;

  prevGuess = 77;
  prevMiss = Math.abs(secretNumber - prevGuess);

  guess = 88;
  miss = Math.abs(secretNumber - guess);

  if     (miss > prevMiss) System.out.println("Colder");
  else if(miss < prevMiss) System.out.println("Warmer");
  else                     System.out.println("No change");

}

Absolute value of difference gives distance between.

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. ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM