TooLargeTooSmall.java 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * Guessing game
  3. * prompts user to guess a mystery number
  4. * after every guess, "Too large" "Too small" "Correct"
  5. * when terminating, display # of guesses
  6. * if the same number is used, it counts as 1 guess
  7. */
  8. import java.util.*;
  9. public class TooLargeTooSmall {
  10. public static int randomNumGenerator(){
  11. // this section starts the game by letting the user select
  12. // a game mode
  13. Random num = new Random();
  14. Scanner keyboard = new Scanner(System.in);
  15. System.out.println("Welcome to the guessing game... \n"
  16. + "Select a mode \n"
  17. + "1: Easy (Number between 1-10)\n"
  18. + "2: Normal (Number between 1-20)\n"
  19. + "3: Hard (Number between 1-50)\n"
  20. + "Select by inputing the number");
  21. int gameMode = keyboard.nextInt();
  22. int min = 0;
  23. int max = 0;
  24. switch (gameMode) {
  25. case 2: min = 1;
  26. max = 20;
  27. break;
  28. case 3: min = 1;
  29. max = 50;
  30. break;
  31. default: min = 1;
  32. max = 10;
  33. break;
  34. }
  35. int guessMe = num.nextInt((max - min) + 1) + min;
  36. return guessMe;
  37. }
  38. public static void guessing() {
  39. int numberToGuess = randomNumGenerator();
  40. boolean guessFound = false;
  41. int guessCounter = 0,
  42. previousGuess = 0;
  43. Scanner keyboard = new Scanner(System.in);
  44. // While loop until guess is correct.
  45. // guess checker - will check guess against other guesses
  46. // boolean, if currentGuess = previousGuess, repeatGuess = true/false
  47. while (guessFound == false) {
  48. // guess found - returns win message and how many guesses
  49. System.out.println("What's your guess?!");
  50. int currentGuess = keyboard.nextInt();
  51. // if statement to check if guess is correct
  52. if (currentGuess == numberToGuess) {
  53. System.out.println("You guessed the right number!"
  54. + "\n"
  55. + "It took you this many guesses: "
  56. + guessCounter);
  57. guessFound = true;
  58. } else {
  59. // check guess against previous guess update counter
  60. if (currentGuess != previousGuess) {
  61. guessCounter++;
  62. previousGuess = currentGuess;
  63. }
  64. if (currentGuess > numberToGuess) {
  65. System.out.println("Number was too large!");
  66. } else {
  67. System.out.println("Number was too small!");
  68. }
  69. System.out.println("That wasn't the right answer. Guess again!");
  70. }
  71. }
  72. }
  73. }