Keeping random number the same between methods - java

In the following code The first method (generateRandomNumber) generates a random no between 1 and 10. The second method (guessRandomNumber) then allows the user to guess the number. The problem I am having is that when the user guesses the number wrong it generates another random number instead of the inital one. As a result the user could guess and never get it correct even by entering every possible number. Can anyone advise how I would change this.
First method (generating the number):
public static int generateRandomNumber() {
Random random = new Random();
// Declaring int for random number and defaulting to 0
int randomNumber = 0;
// Assigning randomNumber between 1 and 10
randomNumber = random.nextInt(10);
randomNumber++;
return randomNumber;
}// end of generateRandomNumber
Second Method (guessing the number):
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == generateRandomNumber()) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber
Attempt:
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
boolean validNumber=false;
boolean correctGuess=false;
int secretNumber=generateRandomNumber();
do{
do{
try{
validNumber=true;
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
}catch (Exception ex){
System.out.println("Sorry invalid entry...");
//Flush scanner
scanner.next();
validNumber=false;
}
}while (!validNumber);
if (userGuess == secretNumber) {
System.out.println("Guess correct, well done!");
correctGuess=true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess=false;
}
}while (!correctGuess);
}// end ofGuessRandomNumber

You need to generate the random number first, before the user guesses, and store it in a variable. Then, instead of calling generateRandomNumber() in the line
if (userGuess == generateRandomNumber())
you need to compare it with that variable.

You should generate the random number before the first do loop. Keep it in a variable called correctNumber, then test that userGuess == correctNumber.

Related

Can a program repeat when a user ends the program while it is running?

This is a Hi-Lo number guessing game code, and the program ends either when the user gets the correct number or enters -1 while playing the game.
Here, I was wondering if it is possible to make the program run again even after the user enters -1 and the game ends, for example, in a situation where the user feels like restarting the game without finishing the first game.
import java.util.Random;
import java.util.Scanner;
public class HighLowGame {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
int guess = scanner.nextInt();
**//if user enters -1, the game ends
if(guess == -1){
break;
}**
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
count = 0;
System.out.println("Would you like to play the game again?(yes/no): ");
String another = scanner.next();
if (another.equalsIgnoreCase("no")) {
break;
}
// if the user wants to play the game one more time, it starts again
else {
number = generator.nextInt(100) + 1;
System.out.println("Please guess the number(Enter -1 to quit): ");
}
}
}
}
}
You can just put the game into a method, and when the method ends, you just ask them.
Main:
public static void main(String[] args){
boolean flag = true;
while(flag){
play();//play the game
Scanner input = new Scanner(System.in);//read the respound
System.out.println("want to play again?");
if(input.nextLine().equal("no"){//Want to play? BTW: I'm assuming you only enter "no" or "yes"
flag = false;//Don't want to play
}
}
}
And the method:
public static void play(){
//create scanner, variables and a random number
Scanner scanner = new Scanner (System.in);
Random generator = new Random();
int number =generator.nextInt(100) + 1;
int count = 0;
boolean game = true;
//prompt user to enter a number
System.out.println("Please guess the number.(Enter -1 to quit): ");
while(game){
//user enters a number
int guess = scanner.nextInt();
//if user enters -1, the game ends
if(guess == -1){
break;
}
//guessed number is out of range
if(guess>100 || guess<0){
System.out.println("The number should be between 0 and 100.");
}
//guessed number is smaller than the random number
if(guess < number && 0 <= guess && guess <= 100 ){
count++;
System.out.println("That is too low. Please try again.(Enter -1 to quit):");
}
// guessed number is bigger than the random number
else if(guess > number && 0 <= guess && guess <= 100){
count++;
System.out.println("That is too high. Please try again.(Enter -1 to quit):");
}
//guessed number is the same as the random number
else if(guess==number) {
count++;
//displays the message and the attempt count
System.out.println("Congratulations! You got the correct number.");
System.out.println("Your attempt was " + count + " tries.");
}
}
}
BTW: you said when the user enters -1, you end the game, then why in the world do you want to ask the user again ?_?

Java - Need my loop to not only end after three guesses but display the correct number as well

I'm trying to have my loop only occur three times. So if the user doesn't guess the correct number after their third guess then the loop ends which I have but it doesn't display what the number was. I need the number displayed after the third guess but not sure why it's not displaying the correct number.
import java.util.Scanner;
public class GuessNumberDoWhileA {
public static void main(String[] args) {
//Generate random number from 1-10
int number = (int) (Math.random()*9 + 1);
int count = 0;
//Auto Generated Method stub
Scanner Input = new Scanner(System.in);
//Tell the user to guess a number
System.out.println("Guess a number between 1 and 10");
//int guess = -1;
//while (guess != number) {
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number)
System.out.println("Correct the number was " + number);
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
else
System.out.println("The correct number is " + number);
}
System.out.println("The number was " + number);
}
}
You need a boolean variable that can be used to check whether user was able to guess the number correctly or not. Initial value of this boolean variable should be false.
You don't need the last else statement in the loop. If user guesses the number correctly, set the boolean variable to true and break out of the loop. After the loop, check if the boolean variable is false or not. If it is false, that means user was not able to guess the number, so display the correct number to the user.
If user is able to guess the number then the first if statement in the loop will print the correct number on the console and break out of the loop. It will also set the boolean variable to true, so correct number will be printed only once on the console.
boolean guessed = false;
while (count < 3) {
count++;
System.out.print("\nEnter your guess: ");
int guess = Input.nextInt();
if (guess == number) {
System.out.println("Correct the number was " + number);
guessed = true;
break;
}
else if (guess > number)
System.out.println("Your guess is to high try again!");
else if (guess < number)
System.out.println("Your guess is to low try again!");
}
if (!guessed) System.out.println("Number was: " + number);

Can't seem to repeat my low-high game

I am trying to develop a simple high low game that asks the user after playing if they would like to play again. If I remove the outer while loop the logic of the inner loop does exactly what I want it to do, however I am unsure how to wrap the inner loop with an outer loop that will ask the play again question and if the answer is yes put them back into the inner loop. Below is my code.
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0 )
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println ();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
You need to put these initializations into the outer loop:
int guess = -1;
int answer = numb.nextInt(100)+1;
int count = 0;
Otherwise they keep the value from the last game and the inner loop will not be executed any more.
you never reset your guess, sentinel, or answer variables
so (guess != sentinel && guess != answer) always evaluates to false after the first time the game is played, and therefore the inner while loop never executes after the first game
while (guess != sentinel && guess != answer) //this is false after the first game because you don't reset variables
{ ...}
Update for OP comment:
to get your code to do what you want you need to add the resets between the outter and inner while loop like this
while (newgame.equalsIgnoreCase("y"))
{
guess = -1;
answer = numb.nextInt(100)+1;
count = 0;
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{ ...}
}
Replace newgame = scan.nextLine(); by this : newgame = scan.next();
And you need to initialise your variables inside your while loop, so that the flag is reseted to false and the random generate new result to guess.
public class Game
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
String newgame = "y";
while (newgame.equalsIgnoreCase("y")) {
int count = 0; // Placeholder for the guess counter.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100) + 1; // Generates a random number for the game.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
while (guess != sentinel && guess != answer) // Loop that ends when user enters a zero.
{
System.out.println("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0) {
System.out.println("Your guess is too low, guess again");
} else if (guess > answer) {
System.out.println("Your guess is to high, guess again");
}
else if (guess == answer) {
System.out.println();
System.out.println("You guessed correctly, you win!!!");
System.out.println("It took you " + count + " guesses");
}
}
System.out.println();
System.out.println("Play another game: y or n?");
newgame = scan.next();
}
}
}

Do-while loop not waiting for user input?

I'm sure this is something simple that I just can't spot, I have a do while loop prompting the user for an array size, which will be used for the rest of the program. If the user enters the right input, the program continues and works fine, but if the user enters the wrong input...
public static void main(String[] args)
{
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do
{
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
}
catch(InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
If the user enters an invalid input, such as "red", the catch block kicks in and prints "Make sure to enter a valid number." and "Enter an array size." over and over without giving the user a chance to actually enter any input. I figured resetting the arraySize variable would fix it, but it doesn't. I guess the keyboard buffer has stuff in it, but no combination of empty printlns has worked so far.
I've heard that Exceptions shouldn't be used to validate user input. Why is that?
Regardless, it's not relevant to this question, as it is an exercise in Exception handling.
Without using isValid boolean variable and make simple code for input.
int arraySize = 0;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) throw new NegativeArraySizeException();// for negative arry size
break;// loop break when got a valid input
} catch (Exception mistake) {
System.err.println("Invalid input: " + mistake);
}
} while (true);
You can add a keyboard.nextLine(); in the event of exception and it should resolve the issue.
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
catch(Exception mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
Please see if this fix works for you. Scanner has a problem when you are trying to get the string from nextInt function. In this I have fetched the string and parsed to Integer and then handled the Number format exception
public static void main(String[] args) {
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = Integer.parseInt(keyboard.next());
} catch (NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
} catch (InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
} catch (NumberFormatException nfe) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
}
mmuzahid is almost there. But I added a way of checking negative number as well. Try this
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) {
System.out.println("Make sure to enter a valid positive number.");
} else {
break;
}
} catch (Exception mistake) {
System.out.println("Make sure to enter a valid number. Error:" + mistake);
}
} while (true);
Use keyboard.nextLine() and NumberFormatException
do {
// more code
try {
arraySize = Integer.valueOf((keyboard.nextLine()));
} catch (NegativeArraySizeException mistake) {
// more code
isValid = false;
} catch (InputMismatchException mistake) {
// more code
isValid = false;
} catch (NumberFormatException mistake) {
// more code
isValid = false;
}
} while (isValid == false);

Two checks in while loop with Scanner - java

im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i

Categories