第十一章第四题(ArrayList的最大元素)(Largest element of ArrayList)

第十一章第四题(ArrayList的最大元素)(Largest element of ArrayList)

  • 11.4(ArrayList的最大元素)编写以下方法,返回一个整数ArrayList的最大值。如果列表为null或者列表的大小为0,则方法返回null值。
    public static Integer max(ArrayList<Integer> list)
    编写一个测试程序,提示用户输入一个以0结尾的数值序列,调用该方法返回输入的最大数值。
    11.4(Largest element of ArrayList)Write the following method to return the maximum value of an integer ArrayList. If the list is null or the size of the list is 0, the method returns a null value.
    public static Integer max(ArrayList<Integer> list)
    Write a test program to prompt the user to input a value sequence ending with 0, and call this method to return the maximum value.
  • 参考代码:
package chapter11;

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

public class Code_04 {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<Integer> num = new ArrayList<>();
        Scanner input = new Scanner(System.in);
        System.out.print("Enter numbers end with 0: ");
        int number = input.nextInt();
        while (number != 0){
    
    
            num.add(number);
            number = input.nextInt();
        }
        int res = max(num);
        System.out.println("The max number is " + res);
    }
    public static Integer max(ArrayList<Integer> list){
    
    
        if (list.size() == 0 || list == null)
            return 0;
        int ret = list.get(0);
        for (int i = 1;i < list.size();++i)
            if (list.get(i) > ret)
                ret = list.get(i);
        return ret;
    }
}

  • 结果显示:
Enter numbers end with 0: 3 4 5 6 7 2 3 1 0
The max number is 7

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/jxh1025_/article/details/109304393