开发者社区> 问答> 正文

数组获取最大和最小值

数组获取最大和最小值

展开
收起
珍宝珠 2020-02-12 18:05:18 1776 0
2 条回答
写回答
取消 提交回答
  • public class Third {
        public static void main(String[] args) {
            //获取数组最值
            int[] a ={55,22,33,66};
            int max = a[0];
            for (int i = 0; i < a.length; i++) {
                if (max<a[i])
                {
                    max=a[i];
                }
            }
            System.out.println(max);
        }
    }
    
    

    最大值:66

    2020-03-13 21:31:29
    赞同 展开评论 打赏
  • 通过 Collections 类的 Collections.max() 和 Collections.min() 方法来查找数组中的最大和最小值:

    import java.util.Arrays;
    import java.util.Collections;
     
    public class Main {
        public static void main(String[] args) {
            Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
            int min = (int) Collections.min(Arrays.asList(numbers));
            int max = (int) Collections.max(Arrays.asList(numbers));
            System.out.println("最小值: " + min);
            System.out.println("最大值: " + max);
        }
    }
    
    

    以上代码运行输出结果为:

    最小值: 1
    最大值: 9
    
    2020-02-12 18:05:44
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多