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:
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.