I want java to give me random number and user will try to guess it, if the user tries to enter an invalid data type, it will say: "Invalid Input. Integer only. Try Again" and will continue the code, but the code is not pushing through after showing the message even though it has while loop.
My whole chode:
import java.util.*;
public class tine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ranNum = new Random();
boolean Win = false;
int nAttempt = 0;
int number = (int)(Math.random()*50 );
int userInput;
System.out.println("Guess a number from 1-50!");
while (Win == false) {
nAttempt ;
try {
userInput = sc.nextInt();
if (userInput < number && userInput >= 1) {
System.out.println("too low.");
}
else if (userInput > number && userInput <= 50){
System.out.println("too high");
}
else if (userInput == number) {
System.out.println("you got it right in " nAttempt " attemp(s)");
Win = true;
}
else {
throw new InvalidInputException();
}
}
catch (InputMismatchException im) {
System.out.println("Invalid Input. Integer only. Try Again");
userInput = sc.nextInt();
nAttempt--;
}
catch (InvalidInputException iie) {
System.out.println("Number is out of range. Try Again.");
userInput = sc.nextInt();
nAttempt--;
}
}
}
}
class InvalidInputException extends Exception {
InvalidInputException(){
super();
}
}
CodePudding user response:
According to java API specification on Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
While nextInt()
does:
Scans the next token of the input as an int.
Therefore, an input including white spaces will be regarded as multiple inputs, which may not be working as expected.
To fix this, I would suggest scanning the entire line using Scanner.nextLine()
, which "returns the rest of the current line, excluding any line separator at the end";
then parse the line as an integer with Integer.parseInt(String)
, which throws runtime exception NumberFormatException
on illegal patterns, so might as well include that in the catch statement:
try
{
String ln = sc.nextLine();
userInput = Integer.parseInt(ln);
...
}
catch (InputMismatchException | NumberFormatException im)
{...}
catch (InvalidInputException iie)
{...}
Also I'm not seeing the point of reading userInput
inside the catch block, as it will be updated again at the first line of the try block, as another cycle of the while loop begins. Hence I suggest removing them:
catch (InputMismatchException im)
{
System.out.println("Invalid Input. Integer only. Try Again");
// userInput = sc.nextInt();
nAttempt--;
}
catch (InvalidInputException iie)
{
System.out.println("Number is out of range. Try Again.");
// userInput = sc.nextInt();
nAttempt--;
}