需求:
让用户依次录入三个整数,求出三个数中的最大值,并打印到控制台。【使用if】
步骤:
1、创建键盘录入Scanner类的对象
2、获取键盘录入的三个整数数字,分别保存int变量a,b,c中
3、计算a,b,c的最大值
4、打印最大值
代码实现:(四种方式)
public class Test {
public static void main(String[] args) {
//1.创建键盘录入Scanner类的对象
Scanner sc = new Scanner(System.in);
//2.获取键盘录入的三个整数数字,分别保存int变量a,b,c中
System.out.println("请输入第一个整数数字: ");
int a = sc.nextInt();
System.out.println("请输入第二个整数数字: ");
int b = sc.nextInt();
System.out.println("请输入第三个整数数字: ");
int c = sc.nextInt();
//3.计算a,b,c的最大值
/*//方式一:
int temp = (a > b) ? a : b;
int max = (temp > c) ? temp : c;*/
/*//方式二
int max;
if(a>b) {
max = a;
} else {
max = b;
}
if (c > max) {
max = c;
}*/
/*//方式三
int max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}*/
//方式四
int max;
if (a >= b && a >= c) {
max = a;
} else if (b >= a && b >= c) {
max = b;
} else {
max = c;
}
//4.打印最大值
System.out.println("最大值: " + max);
}
}