Reputation:
My code is here:
import java.util.Arrays;
public class Q1102 {
public static void main(String[] args) {
String temp = "1 3 5 7 6";
int[] array1 = new int[temp.length()];
for (int i = 0; i < temp.length(); i += 2) {
int mounth = Integer.parseInt(String.valueOf(temp.charAt(i)));
array1[i] = mounth;
}
System.out.println(Arrays.toString(array1));
}
}
For some strange reason, the program outputs this:
[1, 0, 3, 0, 5, 0, 7, 0, 6]
Can someone please tell me why this occurs, and how to remove the extra zeros?
I've printed out the values that entered the array as they are entered, and there aren't any extra zeros.
Upvotes: 0
Views: 124
Reputation: 1349
Here issue in this line
temp.length()
. It will return9
as astring
length. As you know java takes default value0
. That's why you are getting extra zeros.
import java.util.Arrays;
public class Q1102 {
public static void main(String[] args) {
String temp = "1 3 5 7 6";
int length = (temp.length() + 1)/2;
int[] array1 = new int[length];
for (int i = 0, k = 0; i < temp.length(); i +=2, k++) {
int mounth = Integer.parseInt(String.valueOf(temp.charAt(i)));
array1[k] = mounth;
}
System.out.println(Arrays.toString(array1));
}
Upvotes: 0
Reputation: 201439
You are using character conversion in a way that only works with single digit numbers, it's fragile in a number of ways. Instead, split the String
on whitespace and then parse those tokens. Like,
String temp = "1 3 5 7 6";
String[] tokens = temp.split("\\s+");
int[] array1 = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
array1[i] = Integer.parseInt(tokens[i]);
}
System.out.println(Arrays.toString(array1));
Outputs (as I think you expected)
[1, 3, 5, 7, 6]
Upvotes: 4