如何将此 for 循环转换为 for each

How to convert this for loop into for each

我正在自学如何编码。 这是书中的练习。 我很快就能写出 for 循环。 为什么我很难将这个 for 循环转换为 for each。 我错过了什么或做错了什么。谢谢

/**
 * Exercise 4.75 
 * Add a method busiestHour to LogAnalyzer that returns the busiest hour
 * You can do this by looking into the hour counts array to find the element
 * with the biggest count.
 * Hint: Do you need to check every element to see if you have found the busiest
 * hour? If so, use a for loop or a for-each loop. Which one is better in this case.
 */

public int busiestHour(){
    int max = hourCounts[0];
    int counter = 0;
    for(int index = 0; index < hourCounts.length; index++){
        if(max < hourCounts[index]){
            max = hourCounts[index];
            counter = index; 
        }
    }
    return counter;
}

/**
 * for each version my attempt
 */
public int busiestHour2()
{
   int max = hourCounts[0];
   int counter = 0;
   for(int index : hourCounts){
       if(max < hourCounts[index]){ 
          max = hourCounts[index];
          counter = index;          
       }
    }
   return counter;
}

for-each 遍历元素,您使用的是元素,而不是索引。所以在 for(int index : hourCounts){ 中你的 index 实际上已经是 hourCounts 中的当前元素。换句话说,你有当前小时的计数。例如,如果您遍历一个 String 数组,那么 for-each 循环中的变量声明将是 String 类型,而不是 int。这也意味着您根本无权访问索引,除非您自己这样做。

我不会给出这个问题的解决方案(它也会很丑陋),但我认为这个练习的目的是向您展示 for-each 的局限性以及经典 for-loop 仍然存在的地方这是理由。

如前所述,for each 语句遍历列表或元素数组,提供序列中的下一个 元素 for 语句为列表或数组提供了一个 迭代器 并让程序员决定如何使用该迭代器。

对于您的情况,正确的 for each 语句应该是:

public int busiestHour2()
{
   int max = hourCounts[0];
   int counter = 0;
   int index = 0;
   for(int hourCount : hourCounts){
       if(max < hourCount){ 
          max = hourCount;
          counter = index;          
       }
       index = index + 1;
    }
   return counter;
}