How to restart while loop in Number Guessing Game - java

I'm having a problem with this code.
The issue as I see it is that when the user runs the code and either guesses correctly or uses the max number of attempts, the while loop doesn't kick in and allow the game to restart.
My idea is to reset the counter (attempt) to zero and start again but I'm just getting the exit message with the overall score instead.
int guess = 0;
int attempt = 0;
int number = new Random().nextInt(1000) + 1;
int scorePlayer = 0; int scoreComputer = 0;
boolean repeat;
System.out.println("Hello and welcome to the number guessing game.");
System.out.println("Please guess a number between 1 and 1000");
while(repeat == true){
do{
Scanner scan = new Scanner(System.in);
guess = Integer.parseInt(scan.nextLine());
System.out.println("The number you guessed is "+guess);
attempt++;
if(guess == number){
System.out.println("Congratulations! You got it!!");
scorePlayer++;
System.out.println("Would you like to play again? [YES/NO]");
Scanner a = new Scanner(System.in);
String answer = a.nextLine().toUpperCase();
if (answer != "YES"){
//repeat = false;
System.out.println("Thank you for playing");
System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server");
if (scorePlayer<scoreComputer){
System.out.println("Computer wins!");
}else{
System.out.println("You win!");
}break;
}else{
attempt = 0;
}
}else if(guess < number){
System.out.println("That is incorrect, try a larger number");
}else if(guess > number){
System.out.println("That is incorrect, try a smaller number");
}if(attempt == 10 && guess != number){
System.out.println("That is the max number of guesses allowed");
System.out.println("The number you were looking for is "+number);
scoreComputer++;
System.out.println("Would you like to play again? [YES/NO]");
Scanner b = new Scanner(System.in);
String answer = b.nextLine().toUpperCase();
if (answer != "YES"){
//repeat = false;
System.out.println("Thank you for playing");
System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server");
if (scorePlayer<scoreComputer){
System.out.println("Computer wins!");
}else{
System.out.println("You win!");
}break;
}else{
attempt = 0;
}
}
}while(guess != number || attempt == 0);
repeat = false;
}

Single "=" is an assignment operator, simply change it to the double "==".
while(repeat == true)

In addition to what ugur said, you can simply do
while(repeat)
because repeat is a boolean variable (returning true or false)

Check the last line in the outer loop you are setting repeat=false. So when you break from the inner loop, outer while check for repeat and it is false every time except the first.

Related

One expected line of output is not printed

import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);

Problem producing a new random number at the end of HiLo guessing game

I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?
int answer = (int)(Math.random() * 100 + 1);
int guess = 0;
int guessCount = 0;
boolean playGame = true;
String restart;
Scanner scan = new Scanner(System.in);
while(playGame == true)
{
while (playGame == true)
{
System.out.println("Enter a number between 1 and 100: ");
guess = scan.nextInt();
guessCount ++;
System.out.println(answer);
if (guess < 1 || guess > 100)
{
System.out.println("You have entered an invalid number.");
guessCount --;
} else if (guess == answer)
{
System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
break;
} else if (guess > answer)
{
System.out.println("You've guessed too high! Guess again: ");
} else if (guess < answer)
{
System.out.println("You've guessed too low! Guess again: ");
}
}
System.out.println("Would you like to play again? Y/N");
restart = scan.next();
if (restart.equalsIgnoreCase("Y"))
{
playGame = true;
} else if(restart.equalsIgnoreCase("N"))
{
System.out.println("Thank you for playing!");
break;
}
}
The value in the variable 'answer' remains same since variable is a reference to what you have stored / Initialized or Assigned. It does not manipulate in itself. You have to rewrite the code for e.g. answer = (int)(Math.random()*100+1) at the point before game will be restarted or after it.
You're initializing the answer before the loop, it never changes. You have to assign answer a new value when the user chooses to play a new round. This is not the code I'd write, but here it is:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}

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 ?_?

I need advice to fix my HighLow code in java

Im fairly new to java and im having trouble getting this to loop? The code works fine, its just that after the user guesses correctly the code stops.
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
while (true) {
System.out.println("Hi! Please enter a number between 1-100! (if you would like to quit, please press -1)");
int guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}
}
}
I'm not entirely sure what you're asking, however, from what I can understand, you are looking to get your game to loop continuously until the user wants to stop playing. So what you are looking for is a method which gives the user a choice whether they want to play again. My suggesting is using boolean. The following code demonstrates this for your example:
import java.util.Random;
import java.util.Scanner;
public class Chapter3HighLow {
private static boolean playAgain(){
Scanner sc = new Scanner(System.in);
String usrInput = "";
System.out.println("Play again? (Y/N)");
usrInput = sc.next();
if(usrInput.equalsIgnoreCase("Y")){
return true;
}
else if(usrInput.equalsIgnoreCase("N")){
return false;
}
else{
return false;
}
}
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random(); //gives random numbers each time
int correctNum = random.nextInt(100);
int NumberOfTries = 0; // tells how many guesses it took
int guess1 = 0;
do{
do{
System.out.println("Please guess a number between 1-100!");
guess1 = input.nextInt();
NumberOfTries++; //user enters their guesses
if (guess1 == (-1)) {
break; //breaks the loop if the user enters -1
}
if(guess1 < correctNum){
System.out.println("The number inserted is too low!");
}
else if(guess1 > correctNum){
System.out.println("The number inserted is too high!");
}
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries"); // Tells how many tries it took
}
}while(guess1 != correctNum);
correctNum = random.nextInt(100);
NumberOfTries = 0;
}while(playAgain() == true);
}
}
Read more about methods here.
Read more about the boolean data type here.
Your final else appears to be missing a break. Like
else if(guess1 == correctNum){
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
break; // <-- add this.
}
or you might make that the while condition. Something like,
int guess1 = -1;
while (guess1 != correctNum) {
System.out.println("Hi! Please enter a number between 1-100! "
+ "(if you would like to quit, please press -1)");
guess1 = input.nextInt();
if (guess1 == (-1)) {
break;
}
NumberOfTries++;
if (guess1 < correctNum) {
System.out.println("The number inserted is too low!");
} else if (guess1 > correctNum) {
System.out.println("The number inserted is too high!");
} else if (guess1 == correctNum) {
System.out.println("The number you entered was Correct!!");
System.out.println("It took you " + NumberOfTries + " tries");
}
}
Does it really stop after guessing it right ?

How to use while loop

Ask the user to guess a number until the guess is equal random number. press 0 to quit and ask the user if they want to play again.
My problem, 0 for quit is, not working. How can I make it work with while loop?
thanks
import java.util.Random;
import java.util.Scanner;
public class Guessing
{
public static void main(String[]args){
String playAgain = "y";
final int MAX =100;
int randomNumber;
int numberofGuess = 0;
int guess ;
boolean flag=false;
Scanner input = new Scanner(System.in);
Random rand = new Random();
Scanner inputYes= new Scanner(System.in);
while(playAgain.equalsIgnoreCase("y"))//do
{
System.out.println("Guess a number between 1 and "+ MAX );
randomNumber = rand.nextInt(MAX) +1;
numberofGuess = 0;
System.out.println( "enter a guess(0 to quit):");
guess= input.nextInt();
numberofGuess++;
if(guess >0)
if (guess == randomNumber)
{
System.out.println("you guessed corect.");
System.out.println("you guessed " +numberofGuess+ " times");
}
else if(guess < randomNumber)
System.out.println("you guess is too low.");
else if(guess > randomNumber)
System.out.println("you guess is too high.");
System.out.println("Do you want to play again? (y/n)");
playAgain = inputYes.nextLine();
}//while(playAgain.equalsIgnoreCase("y"));
}
}
Your loop runs until the expression in parantheses is false:
while (true) {
// this will be executed forever
}
while (false) {
// this will never be executed
}
a = 0;
while (a == 0) {
a = 1;
// this will be executed exactly once, because a is not equal 0 on the second run
}
guess = 1
while (guess != 0) {
// this will executed until the user enters "0"
readln(guess);
}
Please keep in mind that this is pseudo code. It will not compile.

Categories