Опитвам се да сумирам всички цифри в масив с a for loop
и a enhanced 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);
}
}
Отговори:
1 за отговор № 1Подобреният цикъл не отчита индексирането - той извлича елемента, така че всичко, от което се нуждаете, е:
for(int item: array2){
count2 += item;
}