2

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);
                }
            }
        }
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82

2 Answers2

4

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));
thibsc
  • 3,747
  • 2
  • 18
  • 38
  • You can also use `List.of(a, b, c)`. Also possible `IntStream.of(a, b, c).max().orElseThrow()`. And `Math.max(a, Math.max(b, c))`. – Zabuzard May 07 '20 at 18:44
1

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);
aatif
  • 147
  • 1
  • 1
  • 8