• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help with logic for a simple program

 
Rob Petterson
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I'm having trouble working out what logic to put into a method called isWarmer().
This is description of what the prog should do:
Write a program that plays �guess the number� as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 � 1000.
The program then displays in a label:
I have a number between 0 and 1000 can you guess my number?
Please enter your first guess
A JTextField should be used to input the guess. As each guess is input the background colour should change to either red or blue.
Red indicates that the user is getting �warmer� and blue indicates that the user is getting "colder."
A JLabel should display either "Too High" or "Too Low" to help the user zero in on the correct answer.
When the user gets the correct answer "Correct!" should be displayed and the JTextField used for input should be changed to uneditable.
A JButton should be provided to allow the user to play the game again. When the Button is clicked, a new random number should be generated and
the input JTextField changed to editable.
Here's my rough code:
//import.....
//public class Guess extends JApplet......
{
int guess, randNum;
//generate random number
// user enters a guess
if(guess.isWarmer())
{
//print message saying Getting Warmer
//change the background colour to blue
}
if(!(guess.isWarmer()))
{
//message saying Getting Colder
//change background colour to red
}
else{
//print Correct Answer
//set textField to uneditable
playAgain();
}
public boolean isWarmer()
{
//not sure what to put here??
}
//playAgain() method defined here.
}
Any ideas,

Rob
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How I'd do it:
You need to save another variable. It would be either previousGuess or previousDifference.
Either way, you need to know what the difference was LAST TIME between the guess and the "magic number". Then you can compare the latest guess & the magic number to see whether the user is getting "warmer" or "colder".
You can get difference by taking the absolute value of (magic - guess).
If new difference is less than old difference, isWarmer() returns "true", otherwise "false".
 
Rob Petterson
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Elouise for unscrambling that for me. I had most of that logic in my brain, all tangled up, but couldn't put it down on paper.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic