Java基础系列 - 查找数组的最大值和最小值

package com.test6;

public class test5 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 31, 4, 5, 6, 7, 88, 9, 11, -1};
        float[] arr2 = {1, 2, 31, 4, 5, 6, 7, 88.88f, 9, 11.1f, -1f};
        ArrayHelper ah = new ArrayHelper();
        ah.GetMinAndMax(arr);
        ah.GetMinAndMax(arr2);
        /** 打印显示
         数组元素包括:1 2 31 4 5 6 7 88 9 11 -1
         数组的最大值是:88
         数组的最小值是:-1
         数组元素包括:1.0 2.0 31.0 4.0 5.0 6.0 7.0 88.88 9.0 11.1 -1.0
         数组的最大值是:88.88
         数组的最小值是:-1.0
         */
    }
}

class ArrayHelper {
    public void GetMinAndMax(int[] arr) {
        int min = arr[0];
        int max = arr[0];
        System.out.print("数组元素包括:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
            if (arr[i] > max)   // 判断最大值
                max = arr[i];
            if (arr[i] < min)   // 判断最小值
                min = arr[i];
        }
        System.out.println();
        System.out.println("数组的最大值是:" + max); // 输出最大值
        System.out.println("数组的最小值是:" + min); // 输出最小值
    }

    public void GetMinAndMax(float[] arr) {
        float min = arr[0];
        float max = arr[0];
        System.out.print("数组元素包括:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
            if (arr[i] > max)   // 判断最大值
                max = arr[i];
            if (arr[i] < min)   // 判断最小值
                min = arr[i];
        }
        System.out.println();
        System.out.println("数组的最大值是:" + max); // 输出最大值
        System.out.println("数组的最小值是:" + min); // 输出最小值
    }
}

  

转载于:https://www.cnblogs.com/smartsmile/p/11549360.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值