Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Extracting a number out of a string in Java

  1. Sep 4, 2010 #1
    I have a string of the form "int,int,int,int" and I want to extract each of those ints into a variable that is an int. I have no idea where to even start (I am learning Java as I make a program for an internship, and my searching has yielded nothing).

  2. jcsd
  3. Sep 4, 2010 #2


    User Avatar
    Gold Member

    You can use String.split(",") to break the string into an array delimited by comma. Then loop through the array and use Integer.parseInt before pushing it into another array.
  4. Sep 4, 2010 #3
    Thank you. You actually made another part much easier by introducing Sting.split to me.

  5. Sep 5, 2010 #4
    Ok, so here is some test code I made to quickly test how this would work:

    String string = "1.5,2.3,0.4,2.45,245.4542,245.875,0.785,0.56765,56765.567";
    String[] stringarray = string.split(",");

    int test;

    for(int i = 0; i<stringarray.length; i++){
    test = Integer.parseInt(stringarray);

    And this is the error I get:
    Exception in thread "main" java.lang.NumberFormatException: For input string: "1.5"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

    at java.lang.Integer.parseInt(Integer.java:458)
    at java.lang.Integer.parseInt(Integer.java:499)
    at test.main(test.java:79)

    Line 79 in my program is "test = Integer.parseInt(stringarray);"

    The API entry for parseInt says " Parses the string argument as a signed decimal integer." Thus, I assumed the decimal nature of my ints would be kept intact. Was that a wrong assumption?

  6. Sep 5, 2010 #5


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    1.5 isn't a signed decimal integer.
  7. Sep 5, 2010 #6
    So...um...how do I convert it to a signed int? What is a signed int? I looked online, and am sort of confused.

  8. Sep 5, 2010 #7


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Common operations for converting real numbers into integers are "truncate" and "round".
  9. Sep 5, 2010 #8
    Ok, (and this is where my total lack of any real knowledge comes in), how do I keep its decimal nature? In reality, these numbers are speeds that will be fed into a physics model for total energy used, so they need to be pretty exact.

    Also, can someone explain exactly what makes an int signed?

    Thanks for all the help,

    EDIT: Ok, further research has sort of explained this to me, and I have come to the conclusion I want to use doubles. So..is there a way to extract a double from a string?

    EDIT2: So it seems I am totally idiotic, as Double.parseDouble is an obvious thing to use. Thanks to all who helped me.
    Last edited: Sep 5, 2010
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook