I pretty new to this programming thing and was wondering how to display something when a person inputs a letter when they should of inputed a number. eg.
Please input a number: j
Incorrect input // This displays when the letter above is inputed
@BigDogDec 18.2005 — #I assume you are asking this about Java, and NOT Javascript. They are VERY VERY different, see sticky at the top of this forum for more info.
To test to see if something is a number, you can try to convert it to a number and see if it throws an exception. Below is an example for an Integer.
try { some_int = Integer.parseInt(some_string_that_is_a_number); System.out.println("some_int is an integer that is equal to " + some_int); } catch(NumberFormatException e) { System.out.println("some_int is NOT an integer!"); } [/CODE]
@WaylanderDec 18.2005 — #Yeah it is java, there is no cmd window to print to in javascript....
While for argument sake catching an exception for does validation work, it isnt considered to be the correct way of programming the logic that your after. For something like a date its generally considered to be ok as the alternative checking is failry involved but for standard checking like numbers, money, telephone numbers its much better to use regular expressions. Exceptions are only supposed to be strictly used to catch actual errors, incorrect user input is not considered to be an error.
[CODE]
... import java.util.RegEx.*; ...
public Int getUsersInt() {
boolean _isValid; String _usersInput; int _usersInt;