HELP ON TWO SMALLEST: intro to CS Write your code in the file TwoSmallest.java.
ID: 3674098 • Letter: H
Question
HELP ON TWO SMALLEST: intro to CS
Write your code in the file TwoSmallest.java. Write your test cases in assign2-testcases.txt. 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
**in ALL cases of error on input, RE-ASK the user for the input until it is correctly entered.** for example meaning if they only input one number after terminating value, they must star over from the BEGINNING.
Explanation / Answer
import java.util.Scanner;
public class TwoSmallest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean flag = false; // to check whether user has entered at least 1 valid number
int firstSmallest;
int secondSmallest;
int num;
System.out.println("Enter set of numbers (-999 to stop)");
// reading first input
num = sc.nextInt();
//initializing both with first num
firstSmallest = num;
secondSmallest = num;
if(num!=-999)
flag = true;
while(num!=-999){
if(num < secondSmallest){
if(num < firstSmallest){
secondSmallest = firstSmallest;
firstSmallest = num;
}else{
secondSmallest = num;
}
}
num = sc.nextInt();
}
if(!flag)
System.out.println("No input!!!");
else{
System.out.println("Two Smallest Numbers are: "+firstSmallest+" and "+secondSmallest);
}
}
}
/*
output:
Enter set of numbers (-999 to stop)
32
45
1
8
9
56
7
45
654
23
-999
Two Smallest Numbers are: 1 and 7
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.