Skip to content
Advertisement

How to Find Smallest Number Based On User Input – Java

I’m trying to find the smallest number from the inputs (5 inputs) of users. However, every time I click run and write down the numbers, the smallest number will always be “0”. Here is my code:

import java.util.Scanner;

public class Q2_9 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int counter = 1;
        double number;
        double smallest = 0;

        Scanner s = new Scanner(System.in);

        while (counter < 6) {
            System.out.println("Enter the number: ");
            number = s.nextDouble();

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

            counter++;

        }

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

        s.close();
    }
}

Advertisement

Answer

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.

Advertisement