Returning to the start of the Program - java

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

Related

Random # Guessing Game Infinite Loop

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

Java guess game. How do I input data validation(range checking) and how do I input guesses?

I have a project Im working on for class. Its a guessing game that gets a random number and the user guesses what it is. Ive got a working version of the project, but according to my instructions, it needs data validation(range checking would be best) and it also needs to display a certain message depending on how many tries it takes the user to guess correctly. If its less than 3, it should say something like "Good job!" If its more than 3 but less than 7, it should say something like "Need more practice." If its more than 7 it should say something like "Need way more practice." I dont want to have to de-construct my whole project, I would like to just add into it, and tweak accordingly. Can someone give me a way of coding these things?
Heres my code:
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max);
System.out.println(" ");
}
public static int calculateRandomValue(int max){
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void main(String[] args){
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
System.out.println("Too low! Guess higher!");
}else if (userEntry > unit) {
System.out.println("Too high! Guess lower!");
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
public static void validateTheData() { }
}
Seems all you need to do is passing counter variable to validateTheData method and output your message, like this:
...
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if( (unit - userEntry) > 10 ){
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
validateTheData(counter);
break;
}
counter++;
}
...
public static void validateTheData(int count) {
if( count < 3){
System.out.println("Good job!");
} else if( count < 7 ){
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}

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

Where to put exception for Java Guessing Game

Hi I'm currently having trouble throwing exceptions on my guessing game code. I want to put an exception for string input (instead of int) and also an exception for entering a number beyond the limit(50). Thanks.
public static void main (String[] args)
{
Random ran = new Random();
int numberToGuess = ran.nextInt(50)+1;
int numberOfTries = 0;
Scanner input = new Scanner (System.in);
int guess;
boolean win = false;
while (win == false)
{
System.out.println("Guess a number from 1 to 50!");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess)
{
win = true;
}
else if (guess < numberToGuess)
{
System.out.println("Too low. Try again.");
}
else if (guess > numberToGuess)
{
System.out.println("Too high. Try again.");
}
}
System.out.println("You got it in " + numberOfTries + " attempt(s)!");
}
Here is a potential solution:
import org.apache.commons.lang3.StringUtils;
import java.util.Random;
import java.util.Scanner;
public class StackOverflow45419907 {
private final Scanner input;
final int numberToGuess;
public StackOverflow45419907() {
this.input = new Scanner(System.in);
numberToGuess = new Random().nextInt(50) + 1;
}
public static void main(String[] args) {
new StackOverflow45419907().playGame();
}
private void playGame() {
int numberOfTries = 0;
int guess = -1;
while (guess != numberToGuess) {
guess = collectGuess();
numberOfTries++;
printClue(guess);
}
System.out.println("You got it in " + numberOfTries + " attempt(s)!");
}
private void printClue(int guess) {
if (guess < numberToGuess) {
System.out.println("Too low. Try again.");
} else if (guess > numberToGuess) {
System.out.println("Too high. Try again.");
}
}
private int collectGuess() {
System.out.println("Guess a number from 1 to 50!");
final String potentialGuess = input.nextLine();
return validateAndParse(potentialGuess);
}
private int validateAndParse(String potentialGuess) {
if (!StringUtils.isNumeric(potentialGuess)) {
throw new IllegalArgumentException("not numeric: " + potentialGuess);
}
final int asInt = Integer.parseInt(potentialGuess);
if (asInt > 50 || asInt < 1) {
throw new IllegalArgumentException("value out of valid range: " + asInt);
}
return asInt;
}
}
I don't really think you need to throw exception. you can use
Scanner#hasNextInt() to validate the input is integer. then assign it to the guess variable and just check if its bigger then 50.
If you really what to throw exception. use
throw new RuntimeException(message) if the input is not an integer or it is larger than 50.
Edit:
I wont use it like that, but I believe you just want to know about the exceptions.
System.out.println("Guess a number from 1 to 50!");
numberOfTries++;
if (!input.hasNextInt())
throw new IllegalArgumentException("Input must be a number");
guess = input.nextInt();
if (guess < 1 || guess > 50)
throw new IllegalArgumentException("Input must be a number from 1 to 50");

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