check if a variable is number

L

Lara

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,,,
 
A

Andrew Thompson

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.
 
C

CodeForTea

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.

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
 
L

Lew

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.

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);
}

}

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top