Reputation: 665
I want to calculate the sum of all odd array indexes, but I'm having some trouble finding the right way to do it.
Here's my code so far:
String id = "9506265088085";
String[] strArray = id.split("");
int[] intArray = new int[strArray.length];
int sum = 0;
for (int i = 0; i < 6; i++) {
if (i%2!=0)
{
sum += Integer.parseInt(String.valueOf(id.charAt(i)));
}}
System.out.println(sum);
Any ideas on why this isn't working, or simpler ways to do it? To clarify I want to add all the numbers in the odd array index positions, so intArray[1] + intArray[3] + intArray[5] + ...
.
Edit: Forgot to mention I only want to add 1, 3, 5, 7, 9, 11 and not 13.
Upvotes: 1
Views: 5495
Reputation: 11
There is no Index 13 in this array as in Java index starts from 0. A solution to calculating the sum of all odd array indexes with Java 8 is:
String id = "9506265088085";
String[] strArray = id.split("");
int sum = IntStream.range(0, strArray.length)
.filter(idx -> idx % 2 == 1)
.map(idx -> Integer.parseInt(strArray[idx]))
.sum();
System.out.println(sum);
Upvotes: 1
Reputation: 950
String id = "9506265088085";
int[] intArray = new int[strArray.length];
int sum = 0;
for (int i = 1; i < id.length(); i+=2) {
sum += Integer.parseInt(String.valueOf(id.charAt(i)));
}
System.out.println(sum);
Upvotes: 3
Reputation: 129537
The other answer is right, you are only looping to 5. However, you're making this overly complicated; there's a neat trick you can use to avoid Integer.parseInt()
and String.valueOf()
:
int sum = 0;
for (int i = 1; i < id.length(); i += 2) {
sum += (id.charAt(i) - '0');
}
Also note that instead of checking i%2
repeatedly, you can simply add 2
to the loop control variable at the end of each iteration (and let it start at 1
so you hit only the odd indices).
Upvotes: 6
Reputation: 5055
Just edited your code:
String id = "9506265088085";
int[] intArray = new int[id.length()];
int sum = 0;
for (int i = 0; i < intArray.length; i++) {
if (i%2!=0)
{
sum += Integer.parseInt(String.valueOf(id.charAt(i));
}}
System.out.println(sum);
Upvotes: 4