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.
edit: I used next(); instead of nextInt(); and it fixed my code
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();
}
}