在Java中循环遍历数组的前20个元素 [英] Loop over the first 20 elements of an array in Java

查看:904
本文介绍了在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.

这篇关于在Java中循环遍历数组的前20个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆