java IF NOT statement - java

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

Related

Java beginner -Trying to let player quit the game

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

Need to validate int; hasNextInt isn't working

I'm working on a homework problem of creating a guessing game. I've got that part working, but we have to validate the input. I've tried using hasNextInt, but I keep getting an error saying "int cannot be dereferenced" and points to the "!guess.hasNextInt" code.
I've tried many iterations, but I still get the same error. The code I'm including is just my most recent try.
How do I get hasNextInt to work or how else should I validate the input?
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
//Validates input
while (!guess.hasNextInt()) {
System.out.println("Invalid response, try again.");
in.next();
}
if (guess == num)
System.out.println("Correct!");
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
}
}
}
i fixed the code:
public static void main(String[] args) {
int num = (int) (Math.random() * 101);
System.out.println(num);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (guess != num) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
if (guess == num) {
System.out.println("Correct!");
break;}
else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
//Validates input
while (!input.hasNextInt()) {
System.out.println("Invalid response, try again.");
input.next();
}
}
}
if the user guessed the number the game ends using break
in while (!guess.hasNextInt()) you were using a integer where it's expect the Scanner input
If you want to parse your number you can use Integer.parseInt() method as shown. Also you are using hasNextInt() incorrectly. You are also not storing in.next() value in any variable.
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int num = (int)(Math.random() * 101);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my Guessing Game!");
int guess = -1;
//Loop goes as long as guess doesn't equal num
while (true) {
System.out.print("Guess a number between 1 and 100: ");
String numberString = input.nextLine();
//Validates input
try {
guess = Integer.parseInt(numberString);
if (guess == num) {
System.out.println("Correct!");
break;
} else if (guess < num)
System.out.println("Your guess was too low");
else
System.out.println("Your guess was too high");
} catch (Exception e) {
System.out.println("Invalid response, try again.");
}
}
}
}

Returning to the start of the Program

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

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

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

Categories

Resources