簡體   English   中英

for循環中的數組

[英]Arrays in for loops

我有一個名為blockHeights的數組,其中包含3個值,即1,2,3。 因此, blockHeights[0]等於1。

我也有一個循環:

for (int i = 1; i <= blockHeights.length; i++)

在第一次循環時,我想在其中創建一個名為totalBlockHeights的變量

int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];

但是,在下一個循環中,我希望更改該變量,以便僅將blockHeights[1]blockHeights[2]在一起,而忽略blockHeights[0]

我將如何去做呢?

嘗試以下操作(我假設第三次迭代應遵循該模式僅包括blockHeights[2] ):

for (int i = 1; i <= blockHeights.length; i++) {
    int totalBlockHeights;
    for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
        totalBlockHeights += blockHeights[j];
    }
    // do whatever
}

好吧,如果您想要數組的總和,而沒有第一個值的數組的總和

int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
    totalBlockHeights += blockHeights[i];
}

System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));

這樣你只循環一次

您可以在兩個for循環外部循環上執行此操作for (int i = 1; i <= blockHeights.length; i++) ,在內部循環(采用變量j)中,您可以像int totalBlockHeights = totalBlockHeights + blockHeights[j] ,對於i<j ,您可以繼續執行for循環。

如btrs20回答

嘗試以下代碼:

public class Loop {

    public static void main(String[] argv) {

        int[] blockHeights = new int[] {1, 2, 3};
        int totalBlockHeights = 0;

        for(int i = 0; i < blockHeights.length; i++) {
            totalBlockHeights = 0;
            for(int j = i; j < blockHeights.length; j++) {
                totalBlockHeights += blockHeights[j];
            }
            System.out.println(totalBlockHeights);
        }
    }

}
    int[] blockHeights = new int[] { 1, 2, 3 };
    int totalBlockHeights = 0;
    int customBlockHeights = 0;

    for (int i = 0; i < blockHeights.length; i++) {
        totalBlockHeights += blockHeights[i];
        if (i == 0) {
            continue;
        }
        customBlockHeights += blockHeights[i];
    }
    System.out.println(totalBlockHeights);
    System.out.println(customBlockHeights);

這將打印:

6
5

您不需要兩個就可以實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM