How to use Do While loop in "Guess my number " game? - java

I'm working on this simple task called "Guess my number" and Im trying to implement my code so when user guesses the right number the application displays "Congratulations " and allow the user to choose whether to play again or not. I think a do while loop will do it, but Im still not sure how to implement that. Any ideas?. Thank you in advanced!
Here's my code that runs just fine.
Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
break;
}
}
}

You can add a boolean flag to set inside your outermost loop to break if the user says "No":
Random random = new Random();
while (true)
{
int randomNumber = random.Next(1, 5);
int counter = 1;
bool retry = true;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}
}
if (!retry) break;
}
and for the do-while version:
bool retry = true;
Random random = new Random();
do
{
int randomNumber = random.Next(1, 5);
int counter = 1;
while (true)
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
Console.WriteLine("Would you like to retry? y/n");
string answer = Console.ReadLine();
if (answer != "y")
{
retry = false;
}
break;
}
}
} while (retry);

Implementing a do.. while loop in your code is easy no much difference
Random random = new Random();
do
{
int randomNumber = random.Next(1, 5);
int counter = 1;
do
{
Console.Write("Guess a number between 1 and 5");
int input = Convert.ToInt32(Console.ReadLine());
if (input < randomNumber)
{
Console.WriteLine("Too low, try again.");
++counter;
continue;
}
else if (input > randomNumber)
{
Console.WriteLine("Too high, try again.");
++counter;
continue;
}
else
{
Console.WriteLine("Congratulations. You guessed the number!");
break;
}
}while (true);
}while (true);
Hope that helps...

Related

How to make a exception that inform the user that the number they input is out of range?

We were given a task by my teacher that will ask user for an input of an integer 1 to 50, I've nearly completed my code but the only thing missing is a catch on informing the user if they input more than 50. Can you help me what is the missing in my code. I've read my handouts there is no such thing as an Exception that limiting a certain amount of integer or whatsoever.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int answer = 28;
int attempts = 0;
boolean condition = false;
System.out.println("Guess a Number 1 - 50:");
do {
condition = true;
try {
int input = scan.nextInt();
scan.nextLine();
if(input > answer) {
System.out.println("Too Big");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else if (input < answer) {
System.out.println("Too Small");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else {
int totalA = attempts + 1;
System.out.println(); //Spacing
System.out.println("Congratulations! "+ "You attempted " + totalA + " times." );
}
} catch (InputMismatchException e) {
System.out.println("Numbers only");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
condition = true;
scan.nextLine();
}
} while(condition);
}
I think it is very important that you know that you can create your own Exception classes that have their specific messages and uses.
For example:
public class NumberTooHighException extends Exception {
public NumberTooHighException() {
super("The number inputted is wayyyy to high...");
}
}
And then you can use your Exception as any other:
if(input > 50)
{
throw new NumberTooHighException(); // Here you throw it...
}
And if you wanna catch it, you wrap your code in a try-catch block. More on that here.
But as the comments hint:
An exception is a way of having a method tell the caller of that
method that something went wrong
So try to avoid using them for specific use cases (as this one for example). Even though yours is homework/schoolwork.
So in order to throw an exception from your code, you need to do this ...
if(input > answer) {
...
throw new IllegalArgumentException("Argument is too big");
...
} else if (input < answer) {
...
throw new IllegalArgumentException("Argument is too small");
...
} else {
...
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int answer = 28;
int attempts = 0;
int maxNumber = 50;
boolean condition = false;
System.out.println("Guess a Number 1 - 50:");
do {
condition = true;
try {
int input = scan.nextInt();
scan.nextLine();
if (input > maxNumber){
throw new InputMismatchException();
}else if(input > answer) {
System.out.println("Too Big");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else if (input < answer) {
System.out.println("Too Small");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
attempts++;
} else {
int totalA = attempts + 1;
System.out.println(); //Spacing
System.out.println("Congratulations! "+ "You attempted " + totalA + " times." );
}
} catch (InputMismatchException e) {
System.out.println("Numbers only");
System.out.println(); //Spacing
System.out.println("Guess a Number 1 - 50:");
condition = true;
scan.nextLine();
}
} while(condition);
}

How to generate a random number after user guess the correct number?

I have written the code below. I have run the program and it allows the user to guess the correct number and return the message successfully. However, I couldn't get it to regenerate a new random number? I also couldn't include an option to ask whether the user wants to quit or not. Please help. Thank you.
import java.util.*;
class CompterAge {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
boolean correctGuess = false;
Random r = new Random();
int randNum = r.nextInt(100-1+1) + 1;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input == "Yes") {
correctGuess = false;
} else {
break;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
}
This code works, I have added another flag variable and corrected some logical errors. See the comments.
boolean correctGuess = false;
boolean endGame = false;
Random r = new Random();
while (!endGame){
int randNum = r.nextInt(101); //Why did you have (100-1+1) + 1 ?? Simple (101) was enough
correctGuess = false;
while (!correctGuess) {
System.out.println("Guess the computer's age: ");
int guess = sc.nextInt();
if ((guess > 0) && (guess <= 100)) {
if (guess > randNum) {
System.out.println("Your guess is bigger than the number. You should go lower.");
correctGuess = false;
} else if (guess < randNum) {
System.out.println("Your guess is smaller than the number. You should go higher.");
correctGuess = false;
} else {
correctGuess = true; //Will exit the Inner Loop
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next().toLowerCase();
if (input.equals("yes")) { //You can not use == for String Comparisons
endGame = false;
} else {
endGame = true;
}
}
} else {
System.out.println("Please enter a number between 1 to 100.");
correctGuess = false;
}
}
}
Your random number generation is done outside of your while loop so when they input that they want to continue the game it should then generate a new number:
System.out.println("Congratulations. You got the number! The number is " + randNum);
System.out.println("Do you wish to continue the game? Yes/No");
String input = sc.next();
if (input.equals("Yes")) {
randNum = r.nextInt(100-1+1) + 1;
correctGuess = false;
} else {
break;
}

How to continue looping of do while after exception

After the programs reads the exception it stops.
A need a little help on how to make it continue to the beginning of the loop.
I tried the continue statement but it did not work or maybe my mistake.
package labexer5a;
import java.util.*;
public class LabExer5A {
public static void main(String[] args) {
int max = 50;
int min = 1;
int secretNumber;
secretNumber = (int)(Math.random() * 49 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
int count = 0;
try{
do{
System.out.println("Guess a number from 1 to 50");
guess = keyboard.nextInt();
count ++;
if(guess == secretNumber){
if(count> 1){
System.out.println("You got it in " + count + " attempt(s)");
}
else{
System.out.println("You got it in " + count + " attempt");
}
}
else if(guess > max){
System.out.println("Out of Range");
}
else if(guess < min){
System.out.println("Out of Range");
}
else if(guess > secretNumber){
System.out.println("Too High. Try Again");
}
else if(guess < secretNumber){
System.out.println("Too Low. Try Again");
}
}
while(guess != secretNumber);
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
}
}
}
Move the try/catch inside the loop and place it around the specific code that throws an exception.
do{
System.out.println("Guess a number from 1 to 50");
try {
guess = keyboard.nextInt();
} catch (InputMismatchException e){
System.out.println("Invalid Input");
keyboard.readLine();
continue;
}
count ++;
// rest of code
while(guess != secretNumber);
I am not sure how you want to handle count when you get an exception, if you want to count every attempt even the incorrect one then move count++ to before you read from the scanner.
Try this:
public class LabExer5A {
public static void main(String[] args) {
int max = 50;
int min = 1;
int secretNumber;
secretNumber = (int)(Math.random() * 49 + 1);
Scanner keyboard = new Scanner(System.in);
// you should initiate the value. If there is no exception, it would be replaced by the value read from console.
int guess = Integer.MAX_VALUE;
int count = 0;
do{
System.out.println("Guess a number from 1 to 50");
try {
guess = keyboard.nextInt();
} catch(InputMismatchException e){
System.out.println("Invalid Input");
// you should really read the input
keyboard.next();
count ++;
continue;
}
count ++;
if(guess == secretNumber){
if(count> 1){
System.out.println("You got it in " + count + " attempt(s)");
}
else{
System.out.println("You got it in " + count + " attempt");
}
}
else if(guess > max){
System.out.println("Out of Range");
}
else if(guess < min){
System.out.println("Out of Range");
}
else if(guess > secretNumber){
System.out.println("Too High. Try Again");
}
else if(guess < secretNumber){
System.out.println("Too Low. Try Again");
}
}
while(guess != secretNumber);
}
}
package labexer5a; import java.util.*;
public class LabExer5A {
public static void main(String[] args) {
int max = 50;
int min = 1;
int secretNumber;
secretNumber = (int)(Math.random() * (max-1) + min);
Scanner keyboard = new Scanner(System.in);
int guess;
int count = 0;
do {
System.out.println("Guess a number from "+min+" to "+max);
try{
guess = keyboard.nextInt();
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
continue;
} finally { // don't forget finally clause to increase count
count ++;
}
if(guess == secretNumber){
if(count> 1){
System.out.println("You got it in " + count + " attempt(s)");
}
else{
System.out.println("You got it in " + count + " attempt");
}
}
else if(guess > max){
System.out.println("Out of Range");
}
else if(guess < min){
System.out.println("Out of Range");
}
else if(guess > secretNumber){
System.out.println("Too High. Try Again");
}
else if(guess < secretNumber){
System.out.println("Too Low. Try Again");
}
}
while(guess != secretNumber);
}
}

Limited number of tries to a simple game?

How would I limit the tries of a simple game to just three? I would think you would use a boolean. But not sure.
import java.util.Scanner;
public class guess {
public static void main(String[] args) {
int randomN = (int) (Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.print("Enter your guess: ");
guess = input.nextInt();
if (guess == randomN) {
System.out.println("You won!");
} else if (guess > randomN) {
System.out.println("Too high");
} else if (guess < randomN) {
System.out.println("Too low");
}
} while (guess != randomN);
}
}
int attempts = 0;
do{
attempts++;
....
}while(guess != randomN && attempts < 3);
Use a flag. Initialize it as 0. If guess is correct then reset it as 0. If not increase by 1. Before each guess, check if flag > 2. If no let continue, if yes break.
You can increment during the failure of a guess. I believe the variable should be located outside of the loop. Then what's left is to add a portion that notifies the user of a failure when guesses run out.
public static void main(String[]args) {
int rNumber = (int)(Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
int tries = 0;
int success = 0;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.println("Enter your guess: ");
guess = input.nextInt();
if(guess == rNumber) {
System.out.println("You guessed right! You win!");
success++;
} else if (guess < rNumber) {
System.out.println("Too low");
tries++;
} else if (guess > rNumber) {
System.out.println("Too high.");
tries++;
}
} while(tries != 3 && success != 1 || success != 1);
}

Java- Using if statement inside a loop

I wrote a small code :
System.out.println("Please enter a number");
int number = scan.nextInt();
if(number == 1) {
System.out.println("Number is 1");
} else if(number == 2) {
System.out.println("Number is 2");
} else {
System.out.println("Invalid selection");
}
When the user enters a number different than 1 and 2, user gets "Invalid selection" message and then code terminates. I don't want it to terminate, I want it to run again until user writes 1 or 2. I tried do-while loop but it become an infinite loop. What are your suggestions?
You can use while loop here
Scanner scanner = new Scanner(System.in);
boolean status = true;
while (status) { // this runs if status is true
System.out.println("Please enter a number");
int number = scanner.nextInt();
if (number == 1) {
System.out.println("Number is 1");
status=false; // when your condition match stop the loop
} else if (number == 2) {
System.out.println("Number is 2");
status=false;// when your condition match stop the loop
} else{
System.out.println("Invalid selection");
}
}
Try this...
int number;
do{
System.out.println("Please enter a number");
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number!=1 && number!=2);
I recommend you check if there is an int with Scanner.hasNextInt() before you call Scanner.nextInt(). And, that makes a nice loop test condition if you use it in a while loop.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (scan.hasNextInt()) {
int number = scan.nextInt();
if (number == 1) {
System.out.println("Number is 1");
break;
} else if (number == 2) {
System.out.println("Number is 2");
break;
} else {
System.out.println("Invalid selection");
}
}
// ...
#Dosher, reposting #Raj_89's answer with correction in while loop condition. Please notice While loop condition
int number = 0;
do{
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number==1 || number==2);

Categories

Resources