Hi,,
If I have this statement:
String firstnum =JOptionPane.showInputDialog("Enter first number");
How can I check if (firstnum) is number or not befor converting the
String to Integer??
Regards,,,
Andrew Thompson - 23 Mar 2007 15:14 GMT
...
> String firstnum =JOptionPane.showInputDialog("Enter first number");
>
> How can I check if (firstnum) is number or not befor converting the
> String to Integer??
You do not have to. You might try it,
and catch the result of failure. If it
fails, it means the string does not
represent an integer.
Andrew T.
CodeForTea@gmail.com - 23 Mar 2007 17:01 GMT
> ...
>
[quoted text clipped - 9 lines]
>
> Andrew T.
private static Pattern p = Pattern.compile("\\d+");
public static void main(String[] args) {
String s = "3456";
Matcher m = p.matcher(s);
int number = 0;
if (m.matches()) {
number = Integer.parseInt(s);
System.out.println("The number entered is = " + number);
} else {
System.out.println("Not a number = " + s);
}
int number2 = 0;
String s2 = "x3456";
m = p.matcher(s2);
if (m.matches()) {
number = Integer.parseInt(s);
System.out.println("The numner entered is = " + number2);
} else {
System.out.println("Not a number = " + s2);
}
}
DK
Lew - 23 Mar 2007 23:01 GMT
>> ...
>>
[quoted text clipped - 32 lines]
>
> }
String s = obtainSomeValueThatMightBeNumeric();
int n;
try
{
n = Integer.parseInt( s );
System.err.println( "Yes a number: \""+ s +"\" = "+ n );
}
catch ( NumberFormatException e )
{
System.err.println( "not a number: \""+ s +"\"" );
}
-- Lew
Lara - 24 Mar 2007 17:04 GMT
Thanls alot 4 u...
God bless u