Reputation: 41
int a = 0;
Scanner sc = new Scanner(System.in);
do {
try {
System.out.println("try to get a num");
a = sc.nextInt();
} catch (Exception e) {
System.out.println("dont type Decimal point");
}
} while (a == 0);
System.out.println(a);
oh I guess its a very simple question...
when I type 2.5
to a
,
I hope it will let me enter a=sc.nextInt()
again,
But it did not operate,
It will repeat "don't type Decimal point" in the end,
I just want to make a function that allows the user to check and re-enter when the input number is not an integer
Thank you for your guidance
Have a nice and happy day
Upvotes: 0
Views: 66
Reputation: 1665
You can check if the Scanner object
has an int
available in its input as the next token.
hasNextInt()
is a scanner function which does just that. Here is the method description:
public boolean hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Here is the code to do this:
int a = 0;
Scanner scanner = new Scanner(System.in);
do
{
System.out.print ("Enter an integer: ");
if (scanner.hasNextInt()) a = scanner.nextInt();
else
{
//Print the error message stating the expected input and input found
System.out.println ("Invalid input.");
System.out.println ("Expected input: integer");
System.out.println ("Found: " + scanner.next());
System.out.println ();
}
} while (a == 0);
System.out.println(a);
In the solution above we have prevented any exception from happening using hasNextInt()
and discarded all the wrong inputs in the else
part using next()
method.
The code you provided can also be updated to work in a similar manner. However, instead of preventing the exception, we will wait for it to happen and then handle the wrong input in the catch
block.
Here is your updated code:
do
{
try
{
System.out.println("Try to get a num");
a = scanner.nextInt();
}
catch (Exception e)
{
//Print the error message stating the expected input and input found
System.out.println ("Invalid input.");
System.out.println ("Expected input: integer");
System.out.println ("Found: " + scanner.next());
System.out.println ();
a = 0;
}
} while (a == 0);
I hope I have helped you. Do comment if you face any problems with this solution.
Upvotes: 1