寻找三个数字中最小值的Java程序

224 阅读1分钟

编写一个Java程序,使用Else If、Nested If和三元操作符在给定的三个数字中找出最小的数字。在这个Java例子中,我们使用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);
}