CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   String to INT (http://www.codingforums.com/showthread.php?t=221838)

Gomez 03-20-2011 02:47 AM

String to INT
 
I am trying to convert a string to int value. Is there anyway to implement a if else statement in this so if the user inputs anything else besides an int . it would display an error. otherwise if the user inputs a string of int's it displays the int's.

Code:

        public static void main(String[] args) {
               
                System.out.println("Enter your string to be converted");
                Scanner Keyboard = new Scanner(System.in);
               
                String S1 = Keyboard.next();
                       
                Integer x = Integer.valueOf(S1);
                System.out.println("The Int is:" + "\n"+ S1 );
}
}


oesxyl 03-20-2011 02:54 AM

Quote:

Originally Posted by Gomez (Post 1067626)
I am trying to convert a string to int value. Is there anyway to implement a if else statement in this so if the user inputs anything else besides an int . it would display an error. otherwise if the user inputs a string of int's it displays the int's.

Code:

        public static void main(String[] args) {
               
                System.out.println("Enter your string to be converted");
                Scanner Keyboard = new Scanner(System.in);
               
                String S1 = Keyboard.next();
                       
                Integer x = Integer.valueOf(S1);
                System.out.println("The Int is:" + "\n"+ S1 );
}
}


java.util.regex, Pattern and Matcher?

best regards

Fou-Lu 03-20-2011 02:44 PM

pattern matching will help you to tell if it is a number, but still won't cast it so you'll still need the parse if you want to treat it as a number.
Just try/catch it instead, its much simpler. Integer.parseint will throw a NumberFormatException if it can't be parsed:
PHP Code:

try
{
   
Integer x Integer.valueOf(S1);
   
System.out.println("The int is: " x);
}
catch (
NumberFormatException ex)
{
    
System.out.println(S1 " is not a number.");




All times are GMT +1. The time now is 09:44 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.