I have a String[], where each element is convertible to an integer. What's the best way I can convert this to an int[]?
int[] StringArrayToIntArray(String[] s)
{
... ? ...
}
I have a String[], where each element is convertible to an integer. What's the best way I can convert this to an int[]?
int[] StringArrayToIntArray(String[] s)
{
... ? ...
}
public static int[] StringArrToIntArr(String[] s) {
int[] result = new int[s.length];
for (int i = 0; i < s.length; i++) {
result[i] = Integer.parseInt(s[i]);
}
return result;
}
Simply iterate through the string array and convert each element.
Note: If any of your elements fail to parse to an int this method will throw an exception. To keep that from happening each call to Integer.parseInt() should be placed in a try/catch block.
With Guava:
return Ints.toArray(Collections2.transform(Arrays.asList(s), new Function<String, Integer>() {
public Integer apply(String input) {
return Integer.valueOf(input);
}
});
Admittedly this isn't the cleanest use ever, but since the Function could be elsewhere declared it might still be cleaner.
This is a simple way to convert a String to an Int.
String str = "15";
int i;
i = Integer.parseInt(str);
Here is an example were you to do some math with an User's input:
int i;
String input;
i = Integer.parseInt(str);
input = JOptionPane.showMessageDialog(null, "Give me a number, and I'll multiply with 2");
JOptionPane.showMessageDialog(null, "The number is: " + i * 2);
Output:
Popup: A dialog with an input box that says: Give me a number, and I'll multiply it with 2.
Popup: The number is: inputNumber * 2