I'm currently working on a program that accepts integer values at one point (using Scanner method nextInt). Of course, if you type "one" instead of "1", the program crashes. I'm trying to get it instead to just to say that it was an invalid input and to try again if it isn't an integer, and continue if the value is an integer. So far I'm using the Scanner method hasNextInt, which determines if the value is an integer and returns a boolean value, but the part I'm having trouble with is continuing if an integer value was inputted. So is it possible to continue the program with the inputted value without having to ask for it again?
Asked
Active
Viewed 352 times
0
-
Please share sample input and output. – dryairship Apr 19 '16 at 13:07
-
3Please post your code... – brso05 Apr 19 '16 at 13:07
-
I would read a string with nextLine, then try catch to parseInt within a while loop, but can you please show your code? There is an 'edit' link under the text of the question. – OneCricketeer Apr 19 '16 at 13:08
-
1read a String,parse to int, catch Exception. – Stultuske Apr 19 '16 at 13:08
-
1Why is `if (scanner.hasNextInt()) { i = scanner.nextInt();}` not acceptable for your case? – Jiri Tousek Apr 19 '16 at 13:13
-
Check http://stackoverflow.com/questions/25962939/how-do-i-ensure-that-scanner-hasnextint-asks-for-new-input?rq=1 – Unknown Apr 19 '16 at 13:14
3 Answers
1
Since you are using java.util.Scanner, there is a method
scanner.hasNextInt();
That checks if there is an integer input.
int value = 0;
if(scanner.hasNextInt()) {
value = scanner.nextInt();
} else {
// handle bad input
}

Column-E
- 96
- 4
0
You could try:
...
Scanner in = new Scanner(System.in);
try {
String intS = in.nextLine();
int intI = Integer.parseInt(intS);
} catch (Exception e) {
System.out.println("Error, no Int!")
//or something
}
...

licklake
- 236
- 4
- 15
0
if (x == (int)x)
{
// Number is integer
}
and try that too
Object x = someApi();
if (x instanceof Integer)
How can I check if a value is of type Integer? and How to check if the value is integer in java?

Community
- 1
- 1

Danyal Sandeelo
- 12,196
- 10
- 47
- 78