编写一个 Java 程序,使用 Else If、嵌套 If 和三元运算符来查找给定三个数字中的最小数字。在此示例中,我们使用 else if 来检查每个数字是否小于另外两个数字。
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
int x, y, z;
sc = new Scanner(System.in);
System.out.println("Please Enter three Numbers: ");
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
if (x < y && x < z) {
System.out.format("\n%d is the Smallest Number", x);
}
else if (y < x && y < z) {
System.out.format("\n%d is the Smallest Number", y);
}
else if (z < x && z < y) {
System.out.format("\n%d is the Smallest Number", z);
}
else {
System.out.println("\nEither any 2 values or all of them are equal");
}
}
}
Please Enter three Numbers:
44
99
128
44 is the Smallest Number
使用嵌套 If 语句查找三个数字中最小值的 Java 程序
package RemainingSimplePrograms;
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
int x, y, z;
sc = new Scanner(System.in);
System.out.println("Please Enter three Numbers: ");
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
if (x - y < 0 && x - z < 0) {
System.out.format("\n%d is Lesser Than both %d and %d", x, y, z);
}
else {
if (y -z < 0) {
System.out.format("\n%d is Lesser Than both %d and %d", y, x, z);
}
else {
System.out.format("\n%d is Lesser Than both %d and %d", z, x, y);
}
}
}
}
Please Enter three Numbers:
98
11
129
11 is Lesser Than both 98 and 129
在此 Java 三个数字中最小值的 示例 中,我们使用了两次三元运算符。第一个检查 x 是否大于 y 和 z,第二个检查 y 是否小于 z。
package RemainingSimplePrograms;
import java.util.Scanner;
public class SmallestofThree2 {
private static Scanner sc;
public static void main(String[] args) {
int x, y, z, smallest;
sc = new Scanner(System.in);
System.out.println("Please Enter three Numbers: ");
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
smallest = ((x < y && x < z)? x: (y < z)?y:z);
System.out.format("Smallest number among three is: %d", smallest);
}
}
