Write a program TwoSmallest.java that takes a set of double command-line arguments and prints the smallest and second-smallest number, in that order. It is possible for the smallest and second-smallest numbers to be the same (if the sequence contains duplicate numbers).

Respuesta :

Limosa

Answer:

The following code is written in java programming language:

public class TwoSmallest {   //define class

   public static void main(String[] args) {     // define main function

       if (args.length < 2) {     //set the if condition

           System.out.println("Enter double values as command line arguments");

       } else {

           double minimum1 = Double.parseDouble(args[0]), minimum2 = Double.parseDouble(args[1]), n;

           if (minimum1 > minimum2) {    //set the if condition

               double temp = minimum1;

               minimum1 = minimum2;

               minimum2 = temp;

           }

           for (int i = 2; i < args.length; i++) {      //set the for loop

               n = Double.parseDouble(args[i]);

               if (n < minimum1) {

                   minimum2 = minimum1;

                   minimum1 = n;

               } else if (n < minimum2) {

                   minimum2 = n;

               }

           }

           System.out.println(minimum1);

           System.out.println(minimum2);

       }

   }

}

Explanation:

Here, we define a class "TwoSmallest" with public modifier.

Then, we define the main method.

Then, we set if condition and pass condition "args.length < 2".

Then we take three double type variable "minimum1", "minimum2" and "n".

Then, we set the if condition and pass condition if "minimum1 > minimum2", then set double type "temp" variable and swap between temp, minimum1 and minimum2.

Then, we set the for loop which is start from 2 and stops at "args.length"

Then, we set if condition and then we set its else part, after that we print the value of minimum1 and minimum2.