在java中显示3个数值,有greater, less和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);
}
}
}

编写涉及所有三个变量的所有条件可能比较麻烦。我将按如下步骤进行:

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

试试这样设置最小值和最大值。

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类方法,请编写自己的方法并以相同的方式使用它们。它们使用ternary operator ?:,它表示对于expr ? a : b,如果表达式为真,则返回a,否则返回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;
}

最后,您可以编写方法来接受任意数量的参数并返回适当的参数。它们首先检查是否为空数组,然后检查是否为空数组。

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;
}
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());
}

相关内容

最新更新