Reputation: 143
I am just starting to write a blackjack game with java. I am trying to get the program to ask the user to enter again if the cash they typed in to start with isn't a valid integer. I see many examples of the try statement with catch, but none of them is working. The program gives the error InputMismatchException cannot be resolved to a type. A thread I have followed is this one, and I have the exact same code, just different variable name. Here it is. Java InputMismatchException
Here is my code:
Scanner input_var=new Scanner(System.in);
System.out.println("Welcome to BlackJack!");
System.out.println("Enter how much money you will start with");
System.out.println("Starting cash must be whole number");
int money=0;
do{
try{
System.out.println("Enter how much money you will start with: ");
money=input_var.nextInt();
}
catch (InputMismatchException e){
System.out.println("Sry, not a valid integer");
input_var.nextInt();
}
input_var.nextLine();
}while (money<=0);
Any help with why my almost exact code isn't working would be greatly appreciated. Thanks for your time and effort.
Upvotes: 0
Views: 277
Reputation: 5695
Consume using input.next()
, as input.nextInt()
doesn't exist. That's the whole point of the Exception.
do{
try{
System.out.println("Enter how much money you will start with: ");
money=input_var.nextInt();
}catch (InputMismatchException e){
System.out.println("Sry, not a valid integer");
input_var.next();
}
}while (money<=0);
Upvotes: 2
Reputation: 342
Maybe you're looking for NumberFormatExcpetion
? It's what gets thrown when converting strings to numbers. Try doing this instead:
Scanner input_var=new Scanner(System.in);
System.out.println("Welcome to BlackJack!");
System.out.println("Enter how much money you will start with");
System.out.println("Starting cash must be whole number");
int money=0;
do {
try {
System.out.println("Enter how much money you will start with: ");
money = Integer.parseInt(input_var.next());
}
catch(NumberFormatException e) {
System.out.println("Sry, not a valid integer");
input_var.next();
}
input_var.next();
} while (money<=0);
Upvotes: 1
Reputation: 151
Remove the input_var.nextInt();
from the try statement and input_var.nextLine();
.
There has to be an import like this import java.util.*
or import java..util.InputMismatchException
.
Which IDE are you using?
Upvotes: 1
Reputation: 331
You can use hasNextInt() within a while loop. While the next input is not an integer, display the "not a valid integer" message and get the next input. When it is an integer, the while loop will break and you can do what you need to do.
Upvotes: 1