This site requires JavaScript, please enable it in your browser!
Greenfoot back
gusbus123
gusbus123 wrote ...

2013/4/25

string to int

gusbus123 gusbus123

2013/4/25

#
how do i convert a given string of numbers into an integer?
Duta Duta

2013/4/25

#
I'm assuming you mean a string like the following?:
String numStr = "173 2643 123 1 6";
If so, do this:
String numStr = "173 2643 123 1 6";
// First we split it into an array
String[] numStrArray = numStr.split(" ");
// What this does is makes numStrArray be:
// {"173", "2643", "123", "1", "6"}
// Now we need to go through the array,
// converting the strings to ints:
int len = numStrArray.length;
int[] numArray = new int[len];
for(int i = 0; i < len; i++) {
    String val = numStrArray[i]
    numArray[i] = Integer.parseInt(val);
}
// Now numArray is:
// {173, 2643, 123, 1, 6}
bourne bourne

2013/4/25

#
Integer.parseInt(String)
gusbus123 gusbus123

2013/4/25

#
is there also a way to do this the other way around? as in integer to string?
bourne bourne

2013/4/25

#
int num; ... String s = num + ""; // (String)num might also work
gusbus123 gusbus123

2013/4/26

#
k ty
You need to login to post a reply.