I need help to compute the two smallest numbers in java?... plzz help.. Usage for arraylist and arrays are not allowed.. The user shall be asked for a terminating value first and will continue to provide inputs and once the user enters the same terminating value the program should output the two smallest numbers from the inputs excluding the terminating value..
Additional Details Could show me how to do it... The sentinel value is the value if entered again by the user shall stop the program and output the two smallest numbers.
package hw4;
public class s1 {
public static void main(String[] args) {
int input;
int min;
int min2;
System.out.print("Enter a value to act as sentinel:");
int sentinel = IO.readInt();
System.out.println("Enter numbers");
input = IO.readInt();
do {
min = input;
min2 = input;
if (input < min) {
min = input;
}
input = IO.readInt();
} while (input != sentinel);
// Return the results
System.out.println("The smallest Number is: " + min);
System.out.println("The second smallest Number is: " + min2);
}
}
I'm assuming this is homework, based on the nature of the question. So ...
Hint: if x
was the smallest and y
is now the smallest, then x
is now the second smallest.
Hint 2: make sure your program works when the smallest and second smallest values are equal.
When you find a new min, save the previous minimum in your min2
variable and then reassign min
to the current input.
if (input < min) {
min2 = min
min = input;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With