SRL Archive - Java Help and Tutorials

How to convert string to int in Java?


rj

2013-09-16 15:33:27

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;
}


CynicRus

2013-09-16 15:45:46

From: Officer Barbrady
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;
}




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

2013-09-16 15:49:09

From: CynicRus

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

2013-09-16 18:12:22

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

2013-09-17 02:57:25

From: Officer Barbrady
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;
}



Use String.charAt() to retrieve the character at a specific index. This is the proper way in Java.