在Java中循环遍历数组的前20个元素

问题描述:

我在这里有这个循环

 for(int i =0; i < prices.length; i++)
  {
        if(prices[i]>largest)
        {
            largest = prices[i];
        }

        else if(prices[i]<smallest)
        {
            smallest= prices[i];
        }
  }

循环整个数组并找到min和最大值。说我想只循环前20个元素我该怎么做?我已经尝试过在这个for循环下放置一个嵌套循环的行,看看我是否遇到过它但我不能。

which loops through the whole array and finds the min and max value. Say I wanted to only loop through the first 20 elements how do I do that? I have tried along the lines of putting a nested loop in under this for loop and seeing if I come across it but I can't.

您可以将需求添加到循环控制条件中:

You could just add the requirement to the loop control condition:

for(int i =0; i < prices.length && i < 20; i++)

这将检查前20个元素其中数组中的数量超过20,但如果少于20项则整个数组。

This would check the first 20 elements where ther are more than 20 in the array, but the whole array if there are less than 20 items.