how to find the smallest number based on user input – java?

Algorithm:

  1. Input the first number and assume it to be the smallest number.
  2. Input the rest of the numbers and in this process replace the smallest number if you the input is smaller than it.

Demo:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        final int LIMIT = 5;
        int counter = 1;
        double number;

        Scanner s = new Scanner(System.in);

        // Input the first number
        System.out.print("Enter the number: ");
        number = s.nextDouble();
        double smallest = number;

        // Input the rest of the numbers
        while (counter <= LIMIT - 1) {
            System.out.print("Enter the number: ");
            number = s.nextDouble();

            if (smallest > number) {
                smallest = number;
            }

            counter++;

        }

        System.out.println("The smallest number is " + smallest);
    }
}

A sample run:

Enter the number: -4040404
Enter the number: 808080
Enter the number: -8080808
Enter the number: 8989898
Enter the number: -8989898
The smallest number is -8989898.0

Note: Do not close a Scanner(System.in) as it also closes System.in and there is no way to open it again.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top