Java beginner -Trying to let player quit the game - java

I'm a beginner making a guessing game and I am trying to let the player quit the game by making their guess -1. Currently, if I enter -1 it says Too low and asks me to keep guessing and the player cannot quit the game until they guess the number.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char choice;
do {
int randomNum = (int) (Math.random() * 100 + 1);
int guess = 0;
while (guess != randomNum) {
System.out.println("Guess a number between 1-100");
guess = scan.nextInt();
if (guess > randoomNum) {
System.out.println("Too high.");
}
else if (guess < randoomNum) {
System.out.println("Too low.");
}
else if (guess > 0) {
System.exit(0);
System.out.println("GAME OVER");
System.out.println("the number was " + randomNum + ".");
}
else {
System.out.println("Correct! Well done!");
}
}
System.out.println("\nPlay again? (Y/N)");
choice = scan.next() .charAt(0);
} while (choice == 'Y' | choice =='y');
System.out.println("GAME OVER");
}

The existing code needs to be modified slightly: the condition with exit should be checked before comparing to the randomNum.
Other issues to be addressed:
Use input for Scanner instance
Perform System.exit after printing goodbye message
Scanner input = new Scanner(System.in);
char choice;
do {
int randomNum = (int) (Math.random() * 100 + 1);
int guess = 0;
while (guess != randomNum) {
System.out.println("Guess a number between 1-100, or -1 to exit");
guess = input.nextInt();
if (guess == -1) {
System.out.println("GAME OVER");
System.out.println("the number was " + randomNum + ".");
System.exit(0);
}
if (guess > randomNum) {
System.out.println("Too high.");
}
else if (guess < randomNum) {
System.out.println("Too low.");
}
else {
System.out.println("Correct! Well done!");
}
}
System.out.println("\nPlay again? (Y/N)");
choice = input.next().charAt(0);
} while (choice == 'Y' || choice =='y');
System.out.println("GAME OVER");

Related

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);
}
}

Do While loops and nested if statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a program that randomly generates a number and the user tries to guess the number. The program keeps count of how many tries it took to guess the right number. The issue that I am having is getting past the while loop. When I run the program, it doesn't go past the while loop until I hit -1, in which case it outputs "Your number is too low". I am not real sure where I went wrong.
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args)
{
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
}
while(userInput != -1);
{
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
System.out.println("The number of tries: " + tries);
}
}
Your nesting and placement of braces is confusing. No wonder you're having problems.
Learn to pay more attention to style and readability.
I did not compile or run your code. I didn't think too deeply to see if you did this correctly. But I might do it more like this:
import java.util.Scanner;
import java.util.Random;
public class DoGuessingGame
{
public static void main(String[] args) {
int number1, userInput; //assign vars
int tries = 0;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in); //define Random and scanner input
System.out.println("Welcome to the Guessing Game!");
System.out.println("-----------------------------");
number1 = rand.nextInt(20) + 1;
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21) {
if(userInput == number1) {
System.out.println("That is the correct number");
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
userInput = -1;
} else if(userInput > number1) {
System.out.println("Your number is too high");
System.out.println("Please try again");
} else if(userInput < number1) {
System.out.println("Your number is too low");
System.out.println("Please try again");
}
} else {
System.out.println("Please enter a number between 1 and 20");
}
} while(userInput != -1);
System.out.println("The number of tries: " + tries);
}
You have an extra pair of braces directly after your do-while loop, as well as a semicolon directly after an if-statement which will alter the flow of your program.
else if(userInput < number1);
Your do/while loop is not doing what you think. You have:
do {
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
} while(userInput != -1);
Code below this point is executing after the do while loop, hence userInput will always be -1 when you reach here!
I think your do.... while loop should look like this
do
{
System.out.println("\nI'm thinking of a number between 1 and 20. Enter -1 if you would like to quit");
userInput = keyboard.nextInt();
tries++;
if (userInput > 0 && userInput < 21)
{
if(userInput == number1)
{
System.out.println("That is the correct number");
tries++;
System.out.println("The Number of tries: " + tries);
System.out.println("Game Over.");
}
else if(userInput > number1)
{
System.out.println("Your number is too high");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
else if(userInput < number1);
{
System.out.println("Your number is too low");
System.out.println("Please try again");
userInput = keyboard.nextInt();
tries++;
}
}
else
{
System.out.println("Please enter a number between 1 and 20");
}
}
while(userInput != -1);

Java HiLo program stops

Right now im making a HiLo game in java and i have a few problems, not sure tho if im doing it right since im very new into java.
I having problem with getting the two ints "answer" and "guess" to the 3rd method.
and i must use 3 methods in this task.
Method 1: asking for what lvl the user wants.
Method 2: The program picks a random number between max and lets the user guess.
Method 3: Will see if the guess is == to answer and if not, it lets the user to try again. and at the same time i have to save all the tries from the user.
import java.util.Scanner;
import java.util.Random;
public class oneagain {
public static void main(String[] args) {
System.out.println("Welcome HiLo!");
System.out.println("What lvl?");
System.out.println("1. Easy (1-10)");
System.out.println("2. Medium (1-100)");
System.out.println("3. Hard (1-1000)");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
int tries = (playGame(choice));
}
public static int playGame(int choice) {
Scanner sc = new Scanner(System.in);
int tries = 0;
if (choice == 1) {
System.out.println("Guess a number between 1 and 10");
int answer = (int) (Math.random() * 11) + 1;
int guess = sc.nextInt();
}
if (choice == 2) {
System.out.println("Guess a number between 1 and 100");
int answer = (int) (Math.random() * 101) + 1;
int guess = sc.nextInt();
}
if (choice == 3) {
System.out.println("Guess a number between 1 and 1000");
int answer = (int) (Math.random() * 1001) + 1;
int guess = sc.nextInt();
}
return tries;
}
public static void giveResponse(int answer, int guess) {
if (choice == 1) {
int tries = 0;
Scanner sc = new Scanner(System.in);
boolean y = false;
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 2) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 3) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
}
}
}
}
}
}
}
}

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 IF NOT statement

import java.util.Random;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("Guess a number betwwen 1 and 1000");
Random rand = new Random();
int secretNumber = rand.nextInt (1000);
Scanner keyboard = new Scanner(System.in);
int guess;
do {
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
} while (guess != secretNumber);
}
}
how can i add to this code a statement, that IF NOT NUMERIC INPUT System.out.println("invalid input, please use type numbers only!")
You should use Scanner's hasNextInt() method to determine if the input is numeric before calling nextInt:
do {
while (!keyboard.hasNextInt()) {
System.out.println("Please enter only numbers.");
keyboard.next(); // Skip the wrong token
}
// Now that the input is valid, read the value:
guess = keyboard.nextInt();
// Put the rest of your logic here
...
} while (guess != secretNumber);
Scanner.nextInt() throws
InputMismatchException if the next token does not match the Integer regular expression, or is out of range
So you should wrap your code around a try-catch with this in mind
I think you want the following wrapped around guess = keyboard.nextInt():
try
{
guess = keyboard.nextInt()
Integer.parseInt(guess);
<your if statements>
} catch(Exception ex)
{
System.out.println("Your comment");
}
You can add a try catch block inside your loop.
do {
try{
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
}
catch(InputMismatchException e){
System.out.prinln("Not a number");
}
} while (guess != secretNumber);
While using a scanner you will never figure out if it is an integer that has been entered or not. It will just wait until the "nextInt" is entered. What you can do is use the
Integer.parseInt() method. It will throw a NumberFormatException if the input string is not an integer.
Make guess a string and use. guess = keyboard.next();
Then use Integer.parseInt(guess) in a try-catch to solve your problem.
public class Game {
public static void main(String[] args) {
System.out.println("Guess a number betwwen 1 and 1000");
Random rand = new Random();
int secretNumber = rand.nextInt (1000);
Scanner keyboard = new Scanner(System.in);
int guess;
do {
if (!keyboard.hasNextInt()) {
System.out.println("invalid input, please use type numbers only!");
return;
}
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
} while (guess != secretNumber);
}
}
import java.util.Random;
import java.util.Scanner;
public class Game {
public static boolean isInteger( String input )
{
try
{
Integer.parseInt( input );
return true;
}
catch( Exception e)
{
return false;
}
}
public static void main(String[] args) {
System.out.println("Guess a number betwwen 1 and 1000");
Random rand = new Random();
int secretNumber = rand.nextInt (1000);
Scanner keyboard = new Scanner(System.in);
int guess=-1;
do {
String g = keyboard.next();
if(isInteger(g)){
guess = Integer.parseInt(g);
if (guess == secretNumber)
System.out.println("You WON!!! Congratulations!");
else if (guess < secretNumber)
System.out.println("Nope, to low");
else if (guess > secretNumber)
System.out.println("Sorry, to high");
}
else{
System.out.println("NaN");
}
} while (guess != secretNumber);
}
}

Categories

Resources