输出数组中最大值的另一种方法

package arraytest;

import java.util.Arrays;

public class arraytest {
    //完成 main 方法
    public static void main(String[] args) {

    // 创建对象,对象名为hello
    arraytest hello = new arraytest();

    // 调用方法并将返回值保存在变量中
    int maxScore=hello.getMaxAge();

    // 输出最大年龄
    System.out.println("最大年龄为:" + maxScore);
}

/*
* 功能:输出学生年龄的最大值
* 方法:通过Arrays.sort对数组进行排序后进行输出,与for循环的方式不同,相比较来说更加简便。
* 参考步骤:
* 1、定义一个整形数组 ages ,保存学生年龄,数组元素依次为 18 ,23 ,21 ,19 ,25 ,29 ,17
* 2、使用Arrays.sort对数组进行排序。
* 3、使用 return 返回最大值,这里的最大值为数组排序完成后的最后一个,直接用ages[ages.length-1]表示。
*/
public int getMaxAge()
{
    int[] ages=new int[]{18 ,23 ,21 ,19 ,25 ,29 ,17};
    Arrays.sort(ages);
    return ages[ages.length-1];
}

猜你喜欢

转载自blog.csdn.net/u012580143/article/details/67056753