Is there a way to find if an entry is indeed a number without using try/catch? I want the program to keep asking the user to enter a number if s/he is "silly" enough to input something else.

System.out.print( "\n¿Edad minima a buscar? " );
edadMinima = input.nextInt();

Thanks!

Recommended Answers

All 5 Replies

get a character. If it doesn't match a character that's equivalent to a numerical character reject it.

Scanner has a hasNextInt() method that will tell you if the input can be read as an int (also has method to test for float if needed). If that returns false you can just consume the input and re-try.

jwenting
You mean to pick any one character from whatever the user inputs? If that's the case, what if the user enters something like 12ab and I pick a number?

Ezzaral
I would like to do something like this:

do
{
System.out.print("Enter number: ");
a = input.nextInt();
} while (a is a number);

can I still use hasNextInt() if I don't know what the value is?

Thanks guys!

Ezzaral
I would like to do something like this:

do
{
System.out.print("Enter number: ");
a = input.nextInt();
} while (a is a number);

can I still use hasNextInt() if I don't know what the value is?

Thanks guys!

Did you read the API documentation for the method? http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt(int)

12ab is a number in my book, but my book uses hexadecimal as a numbering system ;)

So you're going to have to define what a "number" is in your world.
Next you're going to have to define how you want to input that number. If you read one token at a time you'd read 12ab as 4 distinct characters and only put them together to find out what the number was afterwards.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.