编写以下方法,返回一个整数 ArrayList 的最大值。如果列表为null或者列表的大小为0,则方法返回null值。

public static Integer max(ArrayList<Integer> list)

编写一个测试程序,提示用户输入一个以0结尾的数值序列,调用该方法返回输入的最大数值。

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static int max(ArrayList<Integer> list){
        int maxList = list.get(0);
        if(list == null || list.isEmpty())
            return 0;
        for (Integer integer : list) {
            maxList = maxList > integer ? maxList : integer;
        }
        return maxList;
    }
    public static void main(String[] args){
        Scanner scn = new Scanner(System.in);
        System.out.println("请输入一个以0结尾的数值序列");
        ArrayList<Integer> list = new ArrayList<>();
        while(true){
            int x = scn.nextInt();
            if(x == 0)break;
            list.add(x);
        }
        int maxList = max(list);
        System.out.println("该数值序列最大值为:" + maxList);
    }
}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐