Java bootcamp · Lab 06

Maximum in a list

mediumArrayList12 minLesson: ArrayList

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

First number n, then n integers. Print the maximum.

Examples

Example 1
Input
5
3 1 8 2 4
Output
8
Example 2
Input
1
42
Output
42
Hint
  1. ArrayList<Integer> nums = new ArrayList<>(); then a loop or Collections.max.
Show correct code

Peek only after you have tried. You can still Check your own version.

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

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    ArrayList<Integer> nums = new ArrayList<>();
    for (int i = 0; i < n; i++) nums.add(in.nextInt());
    System.out.println(Collections.max(nums));
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.