Hi, I am making a guessing game from the java language. The user is asked to input a number. The number is 1 through a random max number. If the number guessed is correct, then the program should return the number of guesses. If the number guessed is null (the player clicked Cancel), the user should get a “Thanks for trying” message, and should return -1. If the number is too high, the player should get a message telling them that the number is too high and should get to try again. If the number is too low, the user should get a message telling them that the number is too low, and they should get to try again.
The problem is when I input a number my compiler will read it correctly. It will notify me that I entered a number too low or too high, but it wont let me try again unless I start the whole program over. I feel that I need to make some sort of loop to get this done, but how?
The problem is when I input a number my compiler will read it correctly. It will notify me that I entered a number too low or too high, but it wont let me try again unless I start the whole program over. I feel that I need to make some sort of loop to get this done, but how?
Code:
import java.util.*; public class GuessingGame { int maxNumber; /** * Constructor setting the input number * and the max number * @param int num */ public GuessingGame(int num) { String number = ""; maxNumber = num; } /** * Random number between 1 and max is generated for the * user to guess. User is asked to guess a number. If number * guessed was correct then return the number of guesses. */ public void Play() { Random ranNum = new Random(); int correctNum = ranNum.nextInt(maxNumber) + 1; //the correct number guessed equals the max random number Scanner in = new Scanner(System.in); System.out.println("Guess a number"); int number = in.nextInt(); if(number == correctNum) //If number correct, return number of guesses { System.out.println(in.nextInt() + " good guess"); } /** * if number guessed is null or user quits then * return message stating "thanks for playing" and -1 * @return */ else if (number == -1) { System.out.println("Thanks for trying" + -1); } /** * if number guessed is too high, * then return message stating number is too high * and to try again * @return */ else if (number > correctNum) { System.out.println("The number is too high, try again"); } /** * if number guessed too low, then * return message stating number is too low * and to try again * @return */ else if (number < correctNum) { System.out.println("The number is too low, please try again"); } } }
Comment