How to determine smallest and largest number in Java

Numbers
Numbers

A couple of weeks ago a reader asked me for a Java program to read command-line input from the user and then display the smallest value the user has entered. He wanted to use digit ‘0’ to indicate that the user is done entering the data and not to include 0 in the list of numbers entered by the user. Here is the Java code to do this. Bonus: This program also determines the largest value entered by the user.



import java.io.*;
import java.util.*;
public class ReadInputNumbers {
      public static void main (String[] args) {
      System.out.print("Enter numbers. Enter 0 after you have
entered  all numbers. \n");
      BufferedReader br = new BufferedReader( 
                               new InputStreamReader(System.in));
      String numberStr = "1";
      ArrayList inputNumbers = new ArrayList();
      Integer intNumber =-999;		
      while(intNumber != 0){
 	 try {
		numberStr = br.readLine();
		intNumber = new Integer(numberStr);
		if(intNumber != 0){
		   inputNumbers.add(new Integer(numberStr));
		}
	} catch (IOException ioe) {
	   System.out.println("IO error trying to read input!");
	   System.exit(1);
	}catch(NumberFormatException e){
	   System.out.println("You entered an invalid number 
                                   ("+numberStr+").");
	   System.exit(1);
	}
      }
      Collections.sort(inputNumbers);
      Iterator itr = inputNumbers.iterator();
      if(!inputNumbers.isEmpty()){
	 System.out.println("You entered..." + inputNumbers);
	 System.out.println("Smallest value you entered is " + 
                         inputNumbers.get(0));
 	 System.out.println("Largest value you entered is " + 
                        inputNumbers.get(inputNumbers.size()-1));
	}else{
	  System.out.println("You did not enter any number.");
	}
   }
} 



Enjoy.

Image credit:BaylorBear78

Comments 31

Leave a Reply

Your email address will not be published. Required fields are marked *