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

Write your code in the file TwoSmallestjava. We wish to write a program that tak

ID: 3930126 • Letter: W

Question

Write your code in the file TwoSmallestjava. 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).

Explanation / Answer

TwoSmallest.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class TwoSmallest {

   public static void main(String[] args) throws IOException {
       BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
       String line;
       double firstMin = Double.MAX_VALUE;
       double secondMin = Double.MAX_VALUE;
       System.out.print("Enter terminating value: ");
       double quit = Double.parseDouble(r.readLine());
       while (true) {
           System.out.print("Enter a number: ");
           line = r.readLine();
       if(Double.parseDouble(line) == quit){
           break;
       }
       else{
       double d = Double.parseDouble(line);
       if(secondMin > d){
           firstMin = secondMin;
           secondMin = d;
          
       }
       }
       }
       System.out.println("Second Small: "+secondMin);
       System.out.println("First Small: "+firstMin);

   }

}

Output:

Enter terminating value: 123
Enter a number: 17
Enter a number: 23.5
Enter a number: 10
Enter a number: 15.2
Enter a number: 30
Enter a number: 8
Enter a number: 16
Enter a number: 123
Second Small:  8.0
First Small: 10.0