累积输出,如同名称一样

时间:2015-10-01 05:36:38

标签: java arrays for-loop

class Cummulative {
    public static void main(String[] args) {
        int arrayValue[] ={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};

        String arrayAlpha[] ={"A","A","B","C","D","E","F","G","H","I","J","K","L","M","O","P","Q","R","S","T","U","V","X","Y","Z"};

        String newArray[] = {"R","A","G","H","U"};

        int total=0;

        for (int i=0; i<newArray.length; i++) {
            for (int j=0; j<arrayAlpha.length; j++) {
                if (arrayAlpha[j].equals(arrayValue[i])) {
                    total = total+arrayValue[j];
                    System.out.println(newArray[i]+"  "+arrayValue[j]+" "+total);
                }
            }
        }
    }
}

输出应具有以下格式:

A 0 1
B 1 2
c 3 5
D 6 10

1 个答案:

答案 0 :(得分:0)

这是您的问题:if (arrayAlpha[j].equals(arrayValue[i]))

应该是(arrayAlpha[j].equals(newArray[i]))

旁注:使用此代码&#34; A&#34;将返回0.看起来这不是必需的,因此我从arrayAlphaarrayValue中移除了第一个值。

class Cummulative {
    public static void main(String[] args) {
        int arrayValue[] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};

        String arrayAlpha[] ={"A","B","C","D","E","F","G","H","I","J","K","L","M","O","P","Q","R","S","T","U","V","X","Y","Z"};

        String newArray[] = {"R","A","G","H","U"};

        int total=0;

        for (int i=0; i<newArray.length; i++) {
            for (int j=0; j<arrayAlpha.length; j++) {
                if (arrayAlpha[j].equals(newArray[i])) {
                    total += arrayValue[j];
                    System.out.println(newArray[i]+"  "+arrayValue[j]+" "+total);
                }
            }
        }
    }
}