12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import java.util.Scanner;
  2. /**
  3. * Write a description of class Guess here.
  4. *
  5. * @author (your name)
  6. * @version (a version number or a date)
  7. */
  8. public class Game
  9. {
  10. int count;
  11. int randomNumber;
  12. int prevGuess;
  13. /**
  14. * Start game.
  15. */
  16. public Game()
  17. {
  18. }
  19. /**
  20. *
  21. */
  22. public boolean checkGuess(int usersGuess)
  23. {
  24. boolean continuePlay = true;
  25. if ((usersGuess == prevGuess)||(usersGuess < 1)||(usersGuess > 100)){
  26. System.out.println( "Try again!");
  27. //for when the user guesses number outside of range or previous guess
  28. } else if (usersGuess > randomNumber)
  29. {
  30. count++;
  31. prevGuess = usersGuess;
  32. System.out.println ("Too large! Guess again.");
  33. } else if (usersGuess < randomNumber)
  34. {
  35. count++;
  36. prevGuess = usersGuess;
  37. System.out.println ("Too small! Guess again.");
  38. }else{
  39. count++;
  40. prevGuess = usersGuess;
  41. System.out.println ("Correct! " + count + " guesses");
  42. continuePlay = false; //stops the while loop
  43. }
  44. return continuePlay;
  45. }
  46. public void play(){
  47. boolean continuePlay = true;
  48. //reset counter, random number, and previous guess each time game is played
  49. count = 0;
  50. randomNumber = (int)(Math.random() * 100);
  51. prevGuess = 0;
  52. while(continuePlay){
  53. Scanner scanner = new Scanner(System.in);
  54. System.out.println ("Enter guess between 1 and 100.");
  55. int guess = scanner.nextInt();
  56. continuePlay = checkGuess(guess); //true or false is returned from the checkGuess method to continue or stop loop
  57. }
  58. }
  59. }