Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2007

Tip: Looking for answers? Try searching our database.

check if a variable is number

Thread view: 
Lara - 23 Mar 2007 14:54 GMT
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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.