Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is the problem: We wish to write a program that takes a set of numbers and

ID: 3673819 • Letter: T

Question

This is the problem:

We wish to write a program that takes a set of numbers and determines which are the two smallest.

Ask the user for the following information, in this order:

A terminating value (real number). The user will enter this value again later, to indicate that he or she is finished providing input.

A sequence of real numbers. Keep asking for numbers until the terminating value is entered.

Compute and output the smallest and second-smallest real number, in that order. It is possible for the smallest and second-smallest numbers to be the same (if the sequence contains duplicate numbers).

Using the IO module.

Explanation / Answer

  import java.util.Scanner;

public class TwoSmallest
{
    public static void main(String [] args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a terminating value: ");
        double terminator = sc.nextDouble();

        double firstsmallest = Double.POSITIVE_INFINITY;
        double secondsmallest = Double.POSITIVE_INFINITY;

        System.out.println("Enter a number");

        double num;

        while ((num = sc.nextDouble()) != terminator)
        {
            if (num < firstsmallest)
            {
                secondsmallest = firstsmallest;
                firstsmallest = num;
            }
            else if (num < secondsmallest)
            {
                secondsmallest = num;
            }
        }

        System.out.println( firstsmallest );
        System.out.println( secondsmallest );
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote