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.
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);
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.
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?
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);
Related
I don't know if im using the isNaN right but can you guys help me on using it to accept only numbers in inputs
while (true){
System.out.println("first number");
num1=input.nextDouble();
if (num1.isNaN()){
System.out.println("invalid input");
}
else;
break;
}
My issue is that when i input a letter, it is not displaying the invalid input message. It just stops the program because i input a letter which is not the error i want to see
Scanner does not return a NaN when an invalid input is given. Instead it throws an InputMismatchException. You could use a try-catch statement to catch this exception and handle it appropriately.
Alternatively, Scanner also has a hasNextDouble() function. This waits and checks if the next value is valid as a double, without actually consuming it.
So you could write your loop like this:
while (true){
System.out.println("Please input a number:");
if (!input.hasNextDouble()) {
System.out.println("Not a valid number.");
break;
}
double number = input.nextDouble();
System.out.println("Your input: " + number);
}
See the documentation on Scanner.hasNextDouble
I am stuck in an infinite loop with this piece of code. The program generates endless lines of "Enter number 1> Please enter a number." when an invalid input like "a" is entered instead of an integer.
I don't know what's wrong with my boolean variable, everything seems fine to me. Please check it out, thank you so much.
import java.util.*;
public class Adder{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
boolean correctInput=false;
while(!correctInput){
try{
System.out.print("Enter number 1> ");
int num1=sc.nextInt();
System.out.print("Enter number 2> ");
int num2=sc.nextInt();
System.out.println("Sum = "+(num1+num2));
correctInput=true;
}
catch(InputMismatchException e){
System.out.println("Please enter a number.");
correctInput=false;
}
}
}
}
Add sc.nextLine(); statement in your catch block.
If you need to retry then add sc.nextLine(); otherwise you can break the loop as well by putting break; statement in catch block.
I have read user input that must be only of type int, the problem comes when the user enters letter instead of a int. I know how to handle the exception, but I would like to return the scanner read where the user has made a mistake. How can I do?
I already tried with an infinite loop, but it does not work.
try{
System.out.print("enter number: ");
value = scanner.nextInt();
}catch(InputMismatchException e){
System.err.println("enter a number!");
}
While other answers give you correct idea to use loop you should avoid using exceptions as part of your basic logic. Instead you can use hasNextInt from Scanner to check if user passed integer.
System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
scanner.nextLine();// consume incorrect values from entire line
//or
//tastiera.next(); //consume only one invalid token
System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();
A loop is the right idea. You just need to mark a success and carry on:
boolean inputOK = false;
while (!inputOK) {
try{
System.out.print("enter number: ");
numAb = tastiera.nextInt();
// we only reach this line if an exception was NOT thrown
inputOK = true;
} catch(InputMismatchException e) {
// If tastiera.nextInt() throws an exception, we need to clean the buffer
tastiera.nextLine();
}
}
This piece of code is supposed to get an integer number from user and then finish the program. If the user inputs an invalid number, it asks user again.
After catching exception, it uses Scanner.reset() to reset the scanner, but it doesn't work. and it re-throws previous exception.
Scanner in = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter an integer number: ");
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
} catch (InputMismatchException ex) {
System.out.println("Error in your input");
in.reset(); // <----------------------------- [The reset is here]
}
}
I thought Scanner.reset() will reset everything and forget the exception. I put it before asking the user for a new input.
If I get the point wrong, what is the right way?
You misunderstood the purpose of the reset method: it is there to reset the "metadata" associated with the scanner - its whitespace, delimiter characters, and so on. It does not change the state of its input, so it would not achieve what you are looking for.
What you need is a call of next(), which reads and discards any String from the Scanner:
try {
System.out.print("Enter an integer number: ");
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
} catch (InputMismatchException ex) {
System.out.println("Error in your input");
in.next(); // Read and discard whatever string the user has entered
}
Relying upon exceptions to catch exceptional situations is OK, but an even better approach to the same issue would be using has... methods before calling the next... methods, like this:
System.out.print("Enter an integer number: ");
if (!in.hasNextLong()) {
in.next();
continue;
}
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
Per Scanner.reset() javadoc, the method only "resets" locale, radix and delimiter settings. It does not do anything to the data it already read.
I'm helping a friend with a java problem. However, we've hit a snag. We're using Java.Util.Scanner.nextInt() to get a number from the user, asking continiously if the user gives anything else. Only problem is, we can't figure out how to do the error handeling.
What we've tried:
do {
int reloop = 0;
try {
number = nextInt();
} catch (Exception e) {
System.out.println ("Please enter a number!");
reloop ++;
}
} while(reloop != 0);
Only problem is, this loops indefinatly if you enter in something not a number.
Any help?
You can use hasNextInt() to verify that the Scanner will succeed if you do a nextInt(). You can also call and discard nextLine() if you want to skip the "garbage".
So, something like this:
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("int, please!");
sc.nextLine();
}
int num = sc.nextInt();
System.out.println("Thank you! (" + num + ")");
See also:
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
The problem with your code, in addition to the unnecessarily verbose error handling because you let nextInt() throw an InputMismatchException instead of checking for hasNextInt(), is that when it does throw an exception, you don't advance the Scanner past the problematic input! That's why you get an infinite loop!
You can call and discard the nextLine() to fix this, but even better is if you use the exception-free hasNextInt() pre-check technique presented above instead.
if the number is non-int , exception will pop, if not reloop will become 1 , and loop will exit
int reloop = 0;
do {
try {
number = nextInt();
reloop ++;
} catch (Exception e) {
System.out.println ("Please enter a number!");
}}
while(reloop == 0);