Find the maximum of three integers

Viewed 217

I have made a program for finding the greatest of the given three numbers. It works for single digit but it is not working for three digit numbers. Why not?

package practice;
import java.util.Scanner;

public class AllPractice {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        if(a > b) {
            if (a > c) {
                System.out.println("maximum of the given numbers "+a);
            }else {
                if (b > a) {
                    if (b > c) {
                        System.out.println("maximum of the given numbers "+b);
                    }
                }else {
                    System.out.println("maximum of the given numbers "+c);
                }
            }
        }
    }
}
2 Answers

Your code doesn't work because if your variable a is smaller than b, you never enter the first condition.


An easy one line solution/alternative:

int max = Collections.max(Arrays.asList(a, b, c));

Your program will work only if a is greater than b. If you want to use simple if else below code will work.

if(a>b && a>c )
    System.out.println("maximum of the given numbers "+a);
else if (b>a && b>c)
    System.out.println("maximum of the given numbers "+b);
else 
    System.out.println("maximum of the given numbers "+c);
Related