Java_输入三个整数x,y,z,请把这三个数由小到大输出,请写出实现代码。(3种方法)

要求:

输入三个整数x,y,z,请把这三个数由小到大输出。

实现代码:

第1种方法:

import java.util.Scanner;

public class xyzMaxMin{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入3个整数:");
		int x = sc.nextInt();
		int y = sc.nextInt();
		int z = sc.nextInt();
		System.out.println("从小到大排序后的结果:");
		if (x < y && x < z) {
			if (y < z) {
				System.out.println(x + "<" + y + "<" + z);
			} else {
				System.out.println(x + "<" + z + "<" + y);
			}
		} else if (y < x && y < z) {
			if (x < z) {
				System.out.println(y + "<" + x + "<" + z);
			} else {
				System.out.println(y + "<" + z + "<" + x);
			}
		} else {
			if (x < y) {
				System.out.println(z + "<" + x + "<" + y);
			} else {
				System.out.println(z + "<" + y + "<" + x);
			}
		}
	}
}

第2种方法:

import java.util.Scanner;

public class xyzMaxMin{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入3个整数:");
		int x = sc.nextInt();
		int y = sc.nextInt();
		int z = sc.nextInt();
		int i = 0;
		if(x>y){
			i=y;
			y=x;
			x=i;
		}
		if(x>z){
			i=z;
			z=x;
			x=i;
		}
		if(y>z){
			i=z;
			z=y;
			y=i;
		}
	    System.out.println("从小到大排序后的结果:");
	    System.out.println(x+"<"+y+"<"+z);
	}
}

第3种方法:

import java.util.Arrays;
import java.util.Scanner;

public class xyzMaxMin{
	public static void main(String[] args) {
		int[] num = new int[3];
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入3个整数:");
		num[0] = sc.nextInt();
		num[1] = sc.nextInt();
		num[2] = sc.nextInt();
		Arrays.sort(num);
		System.out.println("从小到大排序后的结果:");
		for (int i = 0; i < num.length; i++) {
			System.out.print(num[i]+"\t");
		}
	}
}
发布了68 篇原创文章 · 获赞 84 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44893902/article/details/104998207