Chapter 11 Question 4 (Largest element of ArrayList)

Chapter 11 Question 4 (Largest element of ArrayList)

  • 11.4 (Maximum 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 that prompts the user to enter a sequence of values ​​ending in 0, and call this method to return the maximum value entered.
    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.
  • Reference Code:
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;
    }
}

  • The results show that:
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

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109304393