Extracting a number out of a string in Java

  • Context: Java 
  • Thread starter Thread starter nkk2008
  • Start date Start date
  • Tags Tags
    Java String
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
7 replies · 7K views
nkk2008
Messages
32
Reaction score
0
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).

Thanks,
Nkk
 
Physics news on Phys.org
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.
 
DavidSnider said:
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.

Thank you. You actually made another part much easier by introducing Sting.split to me.


Thanks,
Nkk
 
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++){
System.out.println(stringarray);
test = Integer.parseInt(stringarray);
System.out.println(test);
}

And this is the error I get:
1.5
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?

Thanks
Nkk
 
Hurkyl said:
1.5 isn't a signed decimal integer.

So...um...how do I convert it to a signed int? What is a signed int? I looked online, and am sort of confused.

Thanks,
nkk
 
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,
Nkk

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: