Java实现 输入3个数a,b和c,输出最大的数

239 阅读1分钟

方法一 使用if语句

代码如下(示例):

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in); //创建一个Scanner对象
        System.out.print("分别输入a,b,c的值:"); //输入a,b,c三个数的值
        int a = s.nextInt();
        int b = s.nextInt();
        int c = s.nextInt();
        s.close();
        System.out.println("a,b,c的值分别为:" + a + " "+ b + " "+ c);
        if(a>b)
        {
            if(a>c){
                System.out.println("三个数中的最大值为"+a);
            }else{
                System.out.println("三个数中的最大值为"+c);
            }
        }else if(b>c){
            System.out.println("三个数中的最大值为"+b);
            }else{
            System.out.println("三个数中的最大值为"+c);
        }   
    }
}

或者

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
            Scanner s = new Scanner(System.in); //创建一个Scanner对象
            System.out.print("分别输入a,b,c的值:"); //输入a,b,c三个数的值
            int a =s.nextInt();
            int b =s.nextInt();
            int c =s.nextInt();
            s.close();
            System.out.println("a,b,c的值分别为:" + a + " "+ b + " "+ c);
            int max = 0;
            if(a < b) {
                max = b;
            } 
            if(max < c) {
                max = c;
            }
            System.out.println("三个数中的最大值为" + max);
    }
}

方法二 使用三元表达式

代码如下(示例):

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
            int a,b,c;
            Scanner s = new Scanner(System.in); //创建一个Scanner对象
            System.out.print("分别输入a,b,c的值:"); //输入a,b,c三个数的值 
            a =s.nextInt();
            b =s.nextInt();
            c =s.nextInt();
            s.close();
            System.out.println("a,b,c的值分别为:" + a + " "+ b + " "+ c);
            int max = 0;
            max= a>b ? a:b;
            max= c>max ? c:max;
            System.out.println("三个数中的最大值为" + max);
    }
}

方法三 使用构造函数

代码如下(示例):

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
            int a,b,c;
            Scanner s = new Scanner(System.in); //创建一个Scanner对象
            System.out.print("分别输入a,b,c的值:");  //输入a,b,c三个数的值
            a =s.nextInt();
            b =s.nextInt();
            c =s.nextInt();
            s.close();
            /**
             * 使用scanner(system.in)时,使用完毕后
             * 一定要关闭扫描器,因为system.in属于IO流
             * 因为一旦打开的话它就一直在占用内存资源,因此使用完毕后切记要关闭
             */
            System.out.println("三个数中的最大值为:" + getMax(c, getMax(a, b)));
    }
    //构造比较函数getMax
    private static int getMax(int x,int y){
        return x > y ? x : y;
    }   
}

总结

本文简单介绍了用Java语言对三个数求最大值的几种方法,以上代码通过调试均可运行