【问题标题】:Enhanced loop not summing values properly增强的循环没有正确地求和值
【发布时间】:2016-12-02 13:53:23
【问题描述】:

我正在尝试将数组中的所有数字与 for loopenhanced loop 相加。 for loop 工作正常,但 enhanced loop 返回 out of bounds error

按照代码:

import java.util.*;

public class test
{     
  public static void main(String[]args)
  {
     //This code sums all of the values in an array with a for loop

     int count = 0;

     int[] array = {1,2,3,4,5,6,7,8,9,10};        

     for(int item = 0; item<array.length; item++)
        {
           count += array[item];
        }

      System.out.println(Arrays.toString(array) + "\nCount = " + count);
//////////////////////////////////////////////////////////////////////////////
      //This code is supposed to sum all of the digits in an array with a enhanced loop 
      int count2 = 0;

     int[] array2 = {1,2,3,4,5,6,7,8,9,10};        

     for(int item : array2)
        {
           count2 += array2[item];
        }

      System.out.println(Arrays.toString(array2) + "\nCount = " + count2);            
  }
}

【问题讨论】:

  • 在 java 中,item 代表值,这不像 javascript 中 item 代表索引。

标签: java arrays for-loop foreach


【解决方案1】:

增强的循环不计算索引 - 它提取项目本身。所以你只需要:

for(int item: array2){
  count2 += item;
}

【讨论】:

  • 非常感谢您回复@SarTheFirst。您的代码有效。我的 AP 计算机科学课上没有人知道答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 2016-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
相关资源
最近更新 更多