How to find largest and smallest numbers from input in Java
Following simple Java program shows how to read input values and then print smallest and largest values. It reads the input from standard input using Scanner and then uses methods from Math class to determine the largest and smallest numbers entered by the user.
package com.zparacha.utils; import java.util.Scanner; public class LargestSmallestValues { public static void main(String[] args) { try (Scanner in = new Scanner(System.in)) { System.out.print("Please enter numbers:(Enter , to stop)"); double largest = in.nextDouble(); double smallest = largest; while (in.hasNextDouble()) { double input = in.nextDouble(); largest = Math.max(largest, input); smallest = Math.min(smallest, input); } System.out.println("Smallest Value is " + smallest); System.out.println("Largest Value is " + largest); } catch (Exception e) { } } }