用Java语言编写一个程序 输入3个整数,输出其最大值 要求:不能使用if语句

2024-11-07 21:40:02
推荐回答(3个)
回答1:

import java.util.Scanner;
public class test{
    public static void main(String[] args){
        Scanner scan=new Scanner(System.in);
        int[] num=new int[3];
        for(int i=0;i<3;i++){
            System.out.println("请输入第"+(i+1)+"个整数");
            num[i]=scan.nextInt();
        }
        int big=0;
        switch(num[0]>num[1]){
            case true:
            switch(num[1]>num[2]){
                case true:
                big=num[0];
                break;
                case false:
                switch(num[0]>num[2]){
                    case true:
                    big=num[0];
                    break;
                    case false:
                    big=num[2];
                    break;
                }
                break;
            }
            break;
            case false:
            switch(num[2]>num[1]){
                case true:
                big=num[2];
                break;
                case false:
                big=num[1];
                break;
            }
        }
        System.out.println("最大值为:"+big);
    }
}

 我用"switch-case"写的,虽然有点繁琐

回答2:

使用三元运算符,参考代码:

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
        int a, b , c, max;
        Scanner sc = new Scanner(System.in);
        a = sc.nextInt();
        b = sc.nextInt();
        c = sc.nextInt();
        max = a>(b>c?b:c)?a:(b>c?b:c);
        System.out.println("max = " + max);
    }
}

回答3:

public class num {

/**
* @param args
*/
public static void main(String[] args) {
double t,max;
Scanner input = new Scanner(System.in);
System.out.println("请输入第一个数");
double num1 = input.nextDouble();
System.out.println("请输入第二个数");
double num2 = input.nextDouble();
System.out.println("请输入第三个数");
double num3 = input.nextDouble();
t = num1>num2? num1:num2;
max = t > num3? t:num3;
System.out.println("max="+max);
}
}
刚刚写的!我用了DOUBLE类型,要用整型,就nextDouble();改成nextInt();就可以了。