首页 > 解决方案 > 求三个整数的最大值

问题描述

我编写了一个程序来查找给定三个数字中的最大值。它适用于单个数字,但不适用于三位数字。为什么不?

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);
                }
            }
        }
    }
}

标签: javaif-statementmax

解决方案


您的代码不起作用,因为如果您的变量a小于b,则您永远不会输入第一个条件。


一个简单的单线解决方案/替代方案:

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

推荐阅读