A simple Java program to find Largest and Smallest number in a Java List.
Let’s see the program first,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author agurchand
*/
public class LargeSmallNumber {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
//create buffer to capture input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//define list and integers
List list = new ArrayList();
int len, largest, smallest, number;
//get the limit from user
System.out.println("Enter the limit (Better give below 10): ");
len = Integer.parseInt(in.readLine());
//get the list from user
System.out.println("Now enter the list:");
for (int i = 0; i < len; i++) {
list.add(Integer.parseInt(in.readLine()));
}
//assign the first value of list into largest, smallest
largest = (int) list.get(0);
smallest = (int) list.get(0);
//now loop through each list and find largest and smallest number in the list
for (Object list1 : list) {
number = (int) list1;
if (number > largest) {
largest = number;
} else if (number < smallest) {
smallest = number;
}
}
System.out.println("Largest Number is : " + largest);
System.out.println("Smallest Number is : " + smallest);
}
}
Read the comments in the above program to understand.
This program first ask you to enter the limit, then it will ask you to enter the value to the List depends on the limit you have entered. Once you have filled the List, it will show what it the Largest and Smallest number you have entered into the list.
Your Output will be:
Enter the limit (Better give below 10): 5 Now enter the list: 65 78 98 21 1 Largest Number is : 98 Smallest Number is : 1
Enjoy the day!