Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Conversion of string into integer in Java

  1. #1
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Conversion of string into integer in Java

    public static void main(String[] args) {
     
    String yourString = "420";
    int yourInt = Integer.parseInt(yourString);
     
    System.out.println(yourInt);
    }
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.


  2. #2
    Junior Member
    Join Date
    Oct 2009
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: How to convert String to int

    Dude you just help me big time now i can finish like 7 programs!

  3. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: How to convert String to int

    If you are unsure of the input, make sure to catch any NumberFormatExceptions that can be thrown when trying to parse something that can't be parsed
    public static void main(String[] args) {
         int yourInt = -1;
        if ( args.length > 0 ){     
            try{
                yourInt = Integer.parseInt(args[0]);
            }catch ( NumberFormatException e ){
                System.out.println("Wrong number...");
                return;
            }
        }else{
            System.out.println("No input....");
            return;
        }
        System.out.println(yourInt);
    }
    Last edited by copeg; October 25th, 2009 at 10:24 PM.

  4. #4
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to convert String to int

    Personally I'd check the input before trying to parse it as exceptions are slow.

    // Json

  5. #5
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: How to convert String to int

    Quote Originally Posted by Json View Post
    Personally I'd check the input before trying to parse it as exceptions are slow.

    // Json
    Good point. Out of curiosity though...according to this benchmark below going through the try/catch block is 10 times faster than validation (with correct input of course). For incorrect input the validation is 2 times faster than try/catch. I know in the real world things are much different, and there are probably other ways that are potentially faster to do validation, but its just food for thought.

    public class ExceptionTest{
     
    	public static void main( String[] args ){
    		String input = "126";
    		long start = System.currentTimeMillis();
     
    		for ( int i = 0 ; i < 100000; i++ ){
    			try{
    				int st = Integer.parseInt(input);
    			}catch ( NumberFormatException e ){
    				//System.out.println("Error");
    			}
    		}
     
    		System.out.println(System.currentTimeMillis() - start );
    		start = System.currentTimeMillis();
    		for ( int i = 0 ; i < 100000; i++ ){
    			if ( !input.matches("[0-9]+") ){
    				//System.out.println("Error");
    			}else{
                                   int st = Integer.parseInt(input);
                            }
     
    		}
    		System.out.println(System.currentTimeMillis() - start );
    	}
    }
    Last edited by copeg; October 26th, 2009 at 01:45 PM.

  6. #6
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to convert String to int

    I updated your code somewhat to add an input checker of my own.

    package uk.co.cdl.testing.io;
     
    public class ExceptionTest1 {
        public static void main(String[] args) {
            String input = "126h";
            long start = System.currentTimeMillis();
     
            for (int i = 0; i < 100000; i++) {
                try {
                    int st = Integer.parseInt(input);
                } catch (NumberFormatException e) {
                    //System.out.println("Error");
                }
            }
     
            System.out.println("Exceptions: " + (System.currentTimeMillis() - start) + "ms");
            start = System.currentTimeMillis();
            for (int i = 0; i < 100000; i++) {
                if (!input.matches("[0-9]+")) {
                    //System.out.println("Error");
                } else {
                    int st = Integer.parseInt(input);
                }
     
            }
            System.out.println("Regexp: " + (System.currentTimeMillis() - start) + "ms");
     
     
            start = System.currentTimeMillis();
            for (int i = 0; i < 100000; i++) {
                if (isDigits(input)) {
                    int st = Integer.parseInt(input);
                }
            }
            System.out.println("isDigits: " + (System.currentTimeMillis() - start) + "ms");
        }
     
        public static boolean isDigits(final String input) {
            if (input == null) {
                return false;
            } else if ("".equals(input)) {
                return false;
            } else {
                for (int i = 0; i < input.length(); ++i) {
                    if (!Character.isDigit(input.charAt(i))) {
                        return false;
                    }
                }
            }
     
            return true;
        }
    }

    In the case where the input is not a number I get the following output.

    Exceptions: 203ms
    Regexp: 141ms
    isDigits: 0ms
    And in the case were the input is a number I get the following output.

    Exceptions: 0ms
    Regexp: 141ms
    isDigits: 0ms
    // Json

  7. The Following User Says Thank You to Json For This Useful Post:

    copeg (October 27th, 2009)

  8. #7
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: How to convert String to int

    Thanks for posting that code Json.

  9. #8
    Junior Member
    Join Date
    Dec 2009
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to convert String to int

    when i tried this code

    String yourString = "Ashar";
    int yourInt = Integer.parseInt(yourString);
     
    System.out.println(yourInt);

    it compiled showing no errors ... however when I run the program i get an exception in thread "main" java.lang.NumberFormatException: for input String "Ashar" along with other things on the console after running the program

    I want to know why that happens ... I thought this statement will give me the ASCII equivalent to the string "Ashar"

  10. #9
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: How to convert String to int

    Quote Originally Posted by Ashar View Post
    when i tried this code

    String yourString = "Ashar";
    int yourInt = Integer.parseInt(yourString);
     
    System.out.println(yourInt);

    it compiled showing no errors ... however when I run the program i get an exception in thread "main" java.lang.NumberFormatException: for input String "Ashar" along with other things on the console after running the program

    I want to know why that happens ... I thought this statement will give me the ASCII equivalent to the string "Ashar"
    No this is designed for converting a String representation of a Numerical value into a numerical value.

    I.e "1" would become integer 1 and "8" would become integer 8 rather than string literals.

    the following would print each of the ascii values.

    public void printAscii(String s){
       for(int i = s.length-1; i > -1; i--)
          System.out.print((int)s.charAt(i));
       System.out.println();
    }

    Chris
    Last edited by Freaky Chris; December 4th, 2009 at 09:27 AM.

  11. The Following User Says Thank You to Freaky Chris For This Useful Post:

    Ashar (December 4th, 2009)

  12. #10
    Junior Member
    Join Date
    Dec 2009
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: How to convert String to int

    Thank you chris

    can you tell me why was it used in a program to read a number .. does JOptioPane always reads strings?
    like this :
     int x = Integer parseInt(JOprionPane.showInputDialog("Enter number") ;

  13. #11
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: How to convert String to int

    JOptionPane.showInputDialog() does indeed always return a String

  14. #12
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to convert String to int

    Or null?

    // Json

  15. #13
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: How to convert String to int

    Well yes or null i suppose, but its a null String lol

  16. #14
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to convert String to int

    hehe

    // Json

  17. #15
    Junior Member
    Join Date
    Jan 2010
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Re: How to convert String to int

    Hi guys, I don't understand a thing...
    Let me give you some code first:

    public class Airplane {
     
    	private String plane, firstLetter, lastLetter;
    	private int nRows;
    	private int columns;
    	String[] windowsSeats;
    	String[] aisleSeats;
     
     
     
    	public Airplane(String plane, int nRows, String firstLetter, String lastLetter) {
    		this.plane=plane;
    		this.nRows=nRows;
    		this.firstLetter=firstLetter;
    		this.lastLetter=lastLetter;
     
     
    		try{
    			this.columns=Integer.parseInt(lastLetter)-Integer.parseInt(firstLetter)+1;
            }catch ( NumberFormatException e ){
                System.out.println("Wrong number...");
                return;
            }
    ...
     
    	}

    I throw it with a kind of main like:

    public class MainExample {
     
     
    	public static void main(String[] args) throws FullFlight, SeatTaken, NoPlane, NoSeat {
     
     
    		FlightManager  fm = new FlightManager();
    		fm.addAirplane("B737-1", 32, "A", "F");
    		fm.addAirplane("B737-2", 42, "A", "F");
     
    		...
    }

    I obtain always the error message.. Can you explain why the conversion (this.columns..) doesn't succeed?

  18. #16
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to convert String to int

    Hello there, its because you are trying to find a numeric value in a string which is the letter "F" or "A", this will always throw a NumberFormatException because neither A or F are numbers.

    If you wish to convert this into their ASCII equivalents you can use this.

    Character.getNumericValue(lastLetter);

    You also need to make sure that lastLetter and firstLetter is a char instead of a String.

    Hope that helps.

    // Json

  19. #17
    Junior Member
    Join Date
    Jan 2010
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Cool Re: How to convert String to int

    Hi Json and thanks for the answer first!
    I understood your thesis but unfortunately I can not change the type of firstLetter and lastLetter. they're passed as String in the function.

    Can I find another way to solve it?
    Take into account that it is a Flight Manager program, the function "addAirplane" receives these 2 String as parameters, and I must be able to, when I make a reservation, understand how many "columns" of seats there are and also for compute the capacity of an airplane (rows*columns).

    I accept any kind of explanation and help.
    Is very important to me to understand because it is part of an exam at univerisity.

    Thanks

  20. #18
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to convert String to int

    If you know that the 2 strings are always going to be 1 character long you can do this.

    char character = firstLetter.charAt(0);

    That will grab the character at the first position in the string and then you can use that to get the int value.

    // Json

  21. The Following User Says Thank You to Json For This Useful Post:

    Daddo (January 23rd, 2010)

Similar Threads

  1. Convert DOC,XLS to PDF with Java
    By comm in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: July 2nd, 2013, 04:10 AM
  2. Typecasting of double variable to integer
    By JavaPF in forum Java Programming Tutorials
    Replies: 2
    Last Post: December 5th, 2010, 03:41 AM
  3. convert arraylist to a hash map
    By nadman123 in forum Collections and Generics
    Replies: 1
    Last Post: July 29th, 2009, 04:24 AM
  4. [SOLVED] How to string a decimal number in Java?
    By Lizard in forum Loops & Control Statements
    Replies: 6
    Last Post: May 14th, 2009, 03:59 PM