You forgot about
- reset
temp to an empty string after parsing to create space for new digits that there will be no space at the end of your line, therefore
if (numbers.charAt(i) == ' ') { ary[j] = Integer.parseInt(temp); j++; }
will not be called, which means you need to call
ary[j] = Integer.parseInt(temp);
once again after the cycle
But a simpler way would be to simply use split(" ") to create a temporary array of tokens and then parse each token into an int , e.g.
String numbers = "12 1 890 65"; String[] tokens = numbers.split(" "); int[] ary = new int[tokens.length]; int i = 0; for (String token : tokens){ ary[i++] = Integer.parseInt(token); }
which can also be shortened with streams added in Java 8 :
String numbers = "12 1 890 65"; int[] array = Stream.of(numbers.split(" ")) .mapToInt(token -> Integer.parseInt(token)) .toArray();
Another approach would be to use Scanner and its nextInt() method to return all integers from your input. Assuming you already know the size of the required array, you can simply use
String numbers = "12 1 890 65"; int[] ary = new int[4]; int i = 0; Scanner sc = new Scanner(numbers); while(sc.hasNextInt()){ ary[i++] = sc.nextInt(); }
Pshemo
source share