计算所有奇数组索引的总和 [英] Calculating the sum of all odd array indexes

查看:126
本文介绍了计算所有奇数组索引的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要计算所有奇数组索引的总和,但我有一些麻烦发现做正确的方式。

I want to calculate the sum of all odd array indexes, but I'm having some trouble finding the right way to do it.

下面是我的code迄今:

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);

这是为什么这是不工作,或者更简单的方式来做到这一点任何想法?为了澄清我想在奇数组索引位置添加所有的数字,因此, intArray [1] + intArray [3] + intArray [5] + ...

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] + ....

编辑:
忘了提,我只想增加1,3,5,7,9,11和13不会

Forgot to mention I only want to add 1, 3, 5, 7, 9, 11 and not 13.

推荐答案

刚刚编辑您的code:

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);

这篇关于计算所有奇数组索引的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆