COMP1400 – Programming for Designers

Class announcements for Programming for Designers

COMP1400 – Programming for Designers random header image

Random Guessing Game Exercise

Posted by on October 10th, 2013 · Uncategorized

I have made this additional exercise for students who would like more practice on using Random (along side ArrayLists, Loops and Conditional Statements). Solutions have been provided but it is strongly recommend you attempt the task yourself before checking them.

Random Guessing Exercise:

This will be a game where you choose a range for a ‘secret number’ to be in and then you will try and guess it! You will be able to use hints, show your old guesses and restart the game with a different range when you have won.

For this exercise you will need to create a new class, call it GuessGame. It will have the following fields.

FIELDS:

  • secretNum: Stores the secret number you will be trying to guess (int)
  • guesses: Stores all the guess that have already been given (ArrayList)

For our constructor we want to specify the range in which our secretNum will be. So we want the following parameters for our constructor.

CONSTRUCTOR PARAMETERS:

  • min: The lowest value the secret number can be (int)
  • max: The largest value the secret number can be (int)

Question: What should we do if the user gives us a max that is less than theĀ min?

In order to play our guessing game we need to write the following methods.

METHODS:

  • guessNum: Takes in a number and returns true if it is the same as the secret number, false otherwise. Remember to record the guess made in our ArrayList!
  • higherOrLower: Takes in a number and prints out whether or not the secret number is higher or lower than the input number.
  • restartGame: Takes in new min and max values and generates a new secret number. Don’t forget to clear your old guesses!
  • printGuesses: Simply prints out all the guesses that have already been made.

Make sure you test your methods as you write them. It will be a lot harder to find any bugs if you try and test your code after writing everything. More code for your bugs to hide in! Once finish think about the following questions.

Questions to think about:

  1. Can you give a reason why it is important to make our secretNum field private? What can a user do if you have it set to public?
  2. Extra exercise: How would you write a second hint method that takes in a number and returns true if the secret number is divisible by that number?
  3. Did you use one method to generate the secret number in a specific range or did you repeat the same code in both your constructor and restartGame method?

 

Solutions: http://www.cse.unsw.edu.au/~tlen803/infs1609/

 

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

You must log in to post a comment.