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); // 輸出最小值
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM