PDA

View Full Version : How to convert string to int in Java?



rj
09-16-2013, 07:33 PM
I tried Integer.parseInt but it's not working for my name meh.. here is the code


public int[] intDigits(long Int)
{
String s;
int [] result;
s = Long.toString(Int);
for (int i = 0; i < s.length(); i++)
{
result[i] = Integer.parseInt(s[(i + 1)]);
}
return result;
}

http://i.imgur.com/nd9S3f9.png

CynicRus
09-16-2013, 07:45 PM
I tried Integer.parseInt but it's not working for my name meh.. here is the code


public int[] intDigits(long Int)
{
String s;
int [] result;
s = Long.toString(Int);
for (int i = 0; i < s.length(); i++)
{
result[i] = Integer.parseInt(s[(i + 1)]);
}
return result;
}

http://i.imgur.com/nd9S3f9.png


String str = "12345";
int[] array = new int[str.length()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.parseInt(str.substring(i, i + 1));
}

rj
09-16-2013, 07:49 PM
String str = "12345";
int[] array = new int[str.length()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.parseInt(str.substring(i, i + 1));
}

Ahh ok so I have to create a new int object array or something

masterBB
09-16-2013, 10:12 PM
Not tested. Not the fastest. but this works well in my head.

public int[] intDigits(long nr)
{
int amountOfDigits = Math.floor(Math.log10(nr)) + 1; //yes, math.floor + 1 instead of math.ceil
int [] result;
for (int i = amountOfDigits; i > 0; i--)
{
result[i] = Math.floor(nr / Math.pow(10, i));
nr -= result[i] * Math.pow(10, i);
}
return result;
}

Daniel
09-17-2013, 06:57 AM
I tried Integer.parseInt but it's not working for my name meh.. here is the code
public int[] intDigits(long Int)
{
String s;
int [] result;
s = Long.toString(Int);
for (int i = 0; i < s.length(); i++)
{
result[i] = Integer.parseInt(s[(i + 1)]);
}
return result;
}

http://i.imgur.com/nd9S3f9.png

Use String.charAt() (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)) to retrieve the character at a specific index. This is the proper way in Java.