Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: String to INT

  1. #1
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

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

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by Gomez View Post
    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

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    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.");

    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •