Write your code in the file TwoLargest.java. We wish to write a program that tak
ID: 3602162 • Letter: W
Question
Write your code in the file TwoLargest.java.
We wish to write a program that takes a set of numbers and determines which are the twolargest.
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 largest and second-largest real number, in that order. It is possible for the largest and second-largest numbers to be the same (if the sequence contains duplicate numbers).
must use IO.read[data type]
you must use IO.output[data type]
you must use IO.output[data type]Answer()
In ALL cases of error on input, RE-ASK the user for the input until it is correctly entered.
Explanation / Answer
TwoLargest.java
import java.util.Scanner;
public class TwoLargest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the terminating value: ");
double exit = scan.nextDouble();
System.out.println("Enter the value: ");
double value = scan.nextDouble();
double firstMax=Double.MIN_VALUE, secondMax=Double.MIN_VALUE;
while(value != exit) {
if (value > firstMax) {
secondMax = firstMax;
firstMax = value;
} else if (value > secondMax) {
secondMax = value;
}
System.out.println("Enter the value: ");
value = scan.nextDouble();
}
System.out.println("Two large numbers are: ");
System.out.println(firstMax);
System.out.println(secondMax);
}
}
Output:
Enter the terminating value:
123
Enter the value:
17.0
Enter the value:
23.5
Enter the value:
10.0
Enter the value:
15.2
Enter the value:
30.0
Enter the value:
8.0
Enter the value:
16.0
Enter the value:
123
Two large numbers are:
30.0
23.5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.