Find the two smallest numbers using java?

I need help to calculate the two smallest numbers in java? ... plzz help .. Use for arraylist and arrays is not allowed. First, the user will be asked to get the final value and will continue to provide input data and once the user enters the same final value, the program should output the two smallest numbers from the inputs, excluding the final value.

Additional information Could show how to do this ... The value of the sentinel device is the value, if the user enters it again, must stop the program and print the two lowest 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); } } 
+4
source share
3 answers

I guess this is homework based on the nature of the question. So...

Hint: if x was the smallest, and y now the smallest, then x now the second smallest.

Tip 2: make sure your program runs when the smallest and second smallest values ​​are equal.

+4
source

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; } 
+3
source

This will work if you need to find only the smallest number, but you need to find the two smallest numbers, so if should look like this:

 if(input < min) { min2 = min; min = input; } else if (input < min2) { min2 = input; } 

And I know that min and min2 need a value at the beginning, so instead of changing your input value each time, just do it the first time. Also, to get this part from do :

 min = input; min2 = input; 
+1
source

Source: https://habr.com/ru/post/1340411/


All Articles