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);
}
}
Related
I'm a beginner at coding in Java and for my practice is a number guessing game.
I have at least 90% of the code right but my only problem is I do not know how I can make it keep the player input answers when instead of an integer, they input a letter or word.
Here's my code:
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Random number = new Random();
int numberToGuess = number.nextInt(50);
int numberOfTries = 0;
int guess;
boolean win = false;
try {
while (win == false) {
System.out.println("Guess a number between 1 to 50:");
guess = s.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess < 0) {
System.out.println("Invalid Number");
} else if (guess >= 51) {
System.out.println("Number Exceeds Limit");
} else if (guess < numberToGuess) {
System.out.println("Too low; Guess again~");
} else if (guess > numberToGuess) {
System.out.println("Too high; Guess again~");
} else {
System.out.println("I think that is incorrect...");
}
}
System.out.println("You Win!");
System.out.println("The Number was:" + numberToGuess);
System.out.println("It took you:" + numberOfTries + " tries");
} catch (InputMismatchException e) {
System.out.println("I think something is wrong...");
} finally {
System.out.println("Please restart the Game if you wish to continue. Sorry for the Inconveniece");
}
}
}
This will work until the user inputs an integer;
boolean flag =true;
while(flag){
try {
Integer.parseInt(new Scanner(System.in).next());
flag=false;
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n");
}
}
For my Java class, I'm supposed to make a random number guessing game. I've been stuck on a loop I created for the past couple of days. The output of the program is always an infinite loop and I can't see why. Any help is very much appreciated.
/*
This program will generate a random number.
It will ask the user to guess what number was generated and say
if the guess is too high or low.
*/
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0)
{
if(userGuess > randNum){
System.out.println("Too high");
}
else if(userGuess < randNum){
System.out.println("Too high");
}
else{
System.out.println("Something is very wrong.");
}
}
if(userGuess == randNum){
success++;
System.out.println("You got it! Play again?");
}
}
}
You put the if that checks if the input is equal to the number outside the while, so the cycle never ends.
Here is the code fixed:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0) {
if(userGuess > randNum) {
System.out.println("Too high");
} else if(userGuess < randNum) {
System.out.println("Too high");
} else if(userGuess == randNum) {
success++;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I fixed it! I added breaks after each fail condition so that I wouldn't get an infinite loop. I tried this earlier, but I kept getting errors.
This is the completed code:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
boolean success = false;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
input.close();
while(success == false){
if(userGuess > randNum) {
System.out.println("Too high,try again");
break;
} else if(userGuess < randNum) {
System.out.println("Too low");
break;
} else if(userGuess == randNum) {
success = true;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I'm new to java and I have a project that I am working on in school. When I run the program, it gives me everything I ask, except the fact that it prints "The number is bigger" above the answer. Is there anything I am missing? Thanks
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
int numberOfGuesses = 0;
int x = 0;
Random rand = new Random();
int randomNumber = rand.nextInt(100) + 1;
while (x != 1) {
System.out.print("Guess an integer between 1 and 100: " );
int guessedNumber = reader.nextInt();
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
}
if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
}
else{
x++;
}
numberOfGuesses++;
}
System.out.println("You're correct! It took" + " " + numberOfGuesses + " " + "guesses.");
}
}
}
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
}
if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
}
else{
x++;
}
TO
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
} else if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
} else{
x++;
}
When the number is bigger, your second if fails and goes to its else part which increments x to 1 and exists the program. put the second if statement as else if.
if (guessedNumber < randomNumber) {
System.out.println("The number is bigger");
}
else if (guessedNumber > randomNumber) {
System.out.println("The number is smaller");
}
else{
x++;
}
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...
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);
}