Java编程基础笔记 —— 如何获取数组中元素的最大值。

操作数组时,经常需要获取数组中元素的最值,下面来学习如何获取数组中元素的最大值。

    public class GetMax {

    public static void main(String[] args) {
        int[] arr = { 10,6,5,3,1 };
        int max = getMax(arr);
        System.out.println("max="+max);
    }         
    
    static int getMax(int[] arr) {
    	int max = arr[0];	//首先假设第一个元素为最大值						
    	
    	//下面通过一个for循环遍历数组中的元素
    	for(int x=1; xmax) {	
    			max = arr[x];
    		}
    	}
    	return max; 	
    }
}

 

你可能感兴趣的:(Java)