/* * Program to search the maximum value from the standard input by using ArrayList. */ package algorithms; import javax.swing.*; import java.util.ArrayList; import java.util.Scanner; public class MaxValue { public static void main(String[]args) { // Read the integers and store them in the list ArrayList<Integer> numbers = readNumbersFromStandInput(); // Echo check System.out.println(numbers); // Find the maximum value Integer max = maxValue(numbers); // And, print it out System.out.println(max); } private static Integer maxValue(ArrayList<Integer> numbers) { // Initial champion Integer champion = numbers.get(0); // Look at each element as a challenger and if the challenger is greater than the champion, // replace the champion with the challenger for ( Integer challenger : numbers){ if ( challenger > champion ) { champion = challenger; } } // Return the champion return champion; } private static ArrayList<Integer> readNumbersFromStandInput() { // Establish a place to store the numbers ArrayList<Integer> numbers = new ArrayList<>(); // Prepare to read the numbers Scanner scanner = new Scanner(System.in); System.out.println("Enter some positive integers, " + "followed by a negative integers"); // Read and store the numbers in the ArrayList Integer readNumber = scanner.nextInt(); while (readNumber >= 0) { numbers.add(readNumber); readNumber = scanner.nextInt(); } // Return the numbers return numbers; } }