显示 java 中大于、小于和等于的 3 个数值

Display 3 numerical values ​in java with greater, less and equal

我试图在这段代码中显示 3 个不同的值,最大的数字,最小的数字,如果所有数字都相同,输出应该显示它们相等,到目前为止我只能显示更大或相等的值,但我不知道如何实现显示更小的值,这种结构可以帮助我实现它还是我应该使用其他类型的结构?

    import java.util.Scanner;

public class values

{
    public static void main(String[] args) 

    {
        int x, y, z;

        Scanner s = new Scanner(System.in);

        System.out.print("First Value:");

        x = s.nextInt();

        System.out.print("Second Value:");

        y = s.nextInt();

        System.out.print("Third Value:");

        z = s.nextInt();

        if (x == y && x == z)
    {
        System.out.println("All numbers are equal");
        
    }
        else if(y > z && y > x)

        {
            System.out.println("The highest value is: "+y);

        }
        else if(x > y && x > z)

        {
            System.out.println("The highest value is: "+x);
        }
        else

        {
            System.out.println("The highest value is: "+z);
        }
    }
}
    if (x == y && x == z) {
        System.out.println("All numbers are equal");
    } else {
        System.out.println("The highest value is: "+ IntStream.of(x, y, z).max().getAsInt());
        System.out.println("The lowest value is: "+ IntStream.of(x, y, z).min().getAsInt());
    }

像这样尝试最小值和最大值。

int x = 10; int y = 20; int z = 30;
int min = Math.min(Math.min(x,y),z);
int max = Math.max(Math.max(x,y),z);

System.out.println("max = " + max);
System.out.println("min = " + min);

版画

max = 30
min = 10

如果您不想使用 Math class 方法,请自己编写并以相同的方式使用它们。这些使用 ternary operator ?: 表示对于 expr ? a : b 如果表达式为真,return a,否则 return b;

public static int max (int x, int y) {
   return x > y ? x : y;
}

public static int min (int x, int  y) {
   return x < y ? x : y;
}

最后,您可以编写方法来获取任意数量的参数和 return 适当的参数。这些首先检查空数组然后检查空数组。

public static int min(int ...v) {
    Objects.requireNonNull(v);
   if (v.length == 0) {
       throw new IllegalArgumentException("No values supplied");
   }
   int min = v[0];
   for(int i = 1; i < v.length; i++) {
       min =  min < v[i] ? min : v[i];
   }
   return min;
}


public static int max(int ...v) {
    Objects.requireNonNull(v);
    if (v.length == 0) {
        throw new IllegalArgumentException("No values supplied");
    }
    int max = v[0];
    for(int i = 1; i < v.length; i++) {
        max =  max > v[i] ? max : v[i];
    }
    return max;
}

写出涉及所有三个变量的所有条件可能会很麻烦。我将按如下方式进行:

  1. 初始化单独的变量以分别存储最高值和最低值。例如int highest = x; int lowest = x;
  2. 将当前最高和当前最低分别与yz进行比较,必要时进行更改。例如highest = y > highest : y ? highest; lowest = y < lowest ? y : lowest;
  3. 所有比较完成后,如果最高值与最低值相同,则所有xyz都相同。