【问题标题】:Arrays in for loopsfor循环中的数组
【发布时间】:2014-09-14 10:44:57
【问题描述】:

我有一个名为 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] 分配给 totalBlockHeights?

标签: java arrays loops for-loop


【解决方案1】:

尝试以下操作(我假设第三次迭代应该只包含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
}

【讨论】:

  • 我就是这么想的 :)
【解决方案2】:

好吧,如果你想要你的数组的总和,以及没有第一个值的数组的总和

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

这样你只循环一次

【讨论】:

    【解决方案3】:

    试试下面的代码:

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

    【讨论】:

      【解决方案4】:
          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
      

      你不需要两个 for 来实现。

      【讨论】:

        【解决方案5】:

        您可以在两个 for 循环外循环 for (int i = 1; i &lt;= blockHeights.length; i++) 上执行此操作,在内循环中(取一个变量 j)您可以像 int totalBlockHeights = totalBlockHeights + blockHeights[j] 一样执行此操作,对于 i&lt;j,您可以继续 for 循环。

        由 btrs20 回答

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-12-03
          • 2017-01-03
          • 2012-04-24
          • 2012-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多