My teacher gave us this MinFinder example, but I'm having a hard time understanding it.
It accomplishes its goal of displaying the smallest number of 5:
MinFinder example code output:
Someone please address my issues with this example:
- I thought only arrays were able to find the min of multiple numbers in Java?
- Explain why an If statement can be used to find the min. And please explain how the If statement in this example works.
- Is it possible for Math.min to be used to find the min of multiple numbers in Java?
(You don't have to answer all 3 issues. I know this is a long post, lol. Any help is appreciated)
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int min = 0;
for (int i = 0; i < 5; i ) {
System.out.print("Enter number: ");
int num = scn.nextInt();
if (i == 0)
min = num;
if (num < min)
min = num;
}
System.out.println("The smallest number is: " min);
scn.close();
CodePudding user response:
If we are continuously getting it from user inside the loop like above then the logic remains is just comparison so in that case we don't need array.
But array/collections is needed when more than two elements involved.
Similarly we can use either math.max() or min() functions or < or > to do the comparison directly.
CodePudding user response:
This code is for finding the lowest number from the numbers entered... If you want to find the largest number then make this minute changes...
if (num > min)
min = num;
Maybe you could also use Math.max()
like this: min = Math.max(num, min)
Now this will show you the maximum number... Also change the names of the variables (such as min to max) and the printing message to "The largest number is: " and you are done...