Write your code in the file TwoSmallest.java. We wish to write a program that ta
ID: 3929255 • Letter: W
Question
Write your code in the file TwoSmallest.java.
We wish to write a program that takes a set of numbers and determines which are the twosmallest.
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).
In ALL cases of error on input, RE-ASK the user for the input until it is correctly entered.
Use the IO Module for user input (No Scanner). Do not use arrays.
Example:
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
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.