方法一 使用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语言对三个数求最大值的几种方法,以上代码通过调试均可运行,如有错误之处,欢迎评论留言指正。
Logo

昇腾计算产业是基于昇腾系列(HUAWEI Ascend)处理器和基础软件构建的全栈 AI计算基础设施、行业应用及服务,https://devpress.csdn.net/organization/setting/general/146749包括昇腾系列处理器、系列硬件、CANN、AI计算框架、应用使能、开发工具链、管理运维工具、行业应用及服务等全产业链

更多推荐