Suppose I have a string "1 23 40 187 298". This string only contains integers and spaces. How can I convert this string to an integer array, which is [1,23,40,187,298]. this is how I tried
public static void main(String[] args) {
String numbers = "12 1 890 65";
String temp = new String();
int[] ary = new int[4];
int j=0;
for (int i=0;i<numbers.length();i++)
{
if (numbers.charAt(i)!=' ')
temp+=numbers.charAt(i);
if (numbers.charAt(i)==' '){
ary[j]=Integer.parseInt(temp);
j++;
}
}
}
but it doesn't work, please offer some help. Thank you!
numbers.split(" ");first, so you have an array of strings and then you can convert them to int'ssplit(..)method: tutorialspoint.com/java/java_string_split.htmString[]nums = numbers.split(" ")Example: numbers = "1 23 40 187 298"; Then nums = {"1", "23", "40", "187", "298"}; Then you can do the following:int[] arrayOfIntegers = new int[nums.length];for (int i = 0; i < nums.length; i++) { arrayOfIntegers[i] = Integer.parseInt(nums[i]); }