91.1k views
0 votes
Two Smallest (20 points). 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). Note: display one number per line. Hint: Double.MAX_VALUE is the largest real number that can be stored in a double variable. java TwoSmallest 17.0 23.0 5.0 1.1 6.9 0.3 0.3 1.1 java TwoSmallest 1.0 35.0 2.0 1.1 6.9 0.3 0.3 6.7 0.3 0.3

1 Answer

2 votes

Answer:

Written in Java

import java.util.*;

public class Main {

public static void main(String args[]) {

int n;

Scanner input = new Scanner(System.in);

n = input.nextInt();

double nums []= new double [n];

for (int i=0; i<n;i++)

{

nums[i] = input.nextDouble();

}

Arrays.sort(nums);

System.out.println("The two smallest are: ");

for (int i=0; i<2;i++)

{

System.out.println(nums[i]);

}

}

}

Step-by-step explanation:

This line declares number of input

int n;

This line calls the Scanner function

Scanner input = new Scanner(System.in);

This line gets input from user

n = input.nextInt();

This line declares an array of n elements

double nums []= new double [n];

The following iteration gets input into the array

for (int i=0; i<n;i++)

{

nums[i] = input.nextDouble();

}

This line sorts the array

Arrays.sort(nums);

The following iteration prints the two smallest

System.out.println("The two smallest are: ");

for (int i=0; i<2;i++)

{

System.out.println(nums[i]);

}

User Sixrandanes
by
4.8k points