题目:输入三个整数x,y,z,请把这三个数由小到大输出?
程序分析
题目要求输入三个整数x, y, z,然后将这三个数按照从小到大的顺序输出。我们可以考虑多种方法实现,包括直接比较、数组排序和使用集合类。
方法一:直接比较大小并输出
解题思路
- 通过比较x、y、z的大小,逐个判断它们的大小关系,并按照从小到大的顺序输出。
代码
import java.util.Scanner;
public class SortNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter x: ");
int x = scanner.nextInt();
System.out.print("Enter y: ");
int y = scanner.nextInt();
System.out.print("Enter z: ");
int z = scanner.nextInt();
if (x <= y && x <= z) {
System.out.print(x + " ");
if (y <= z) {
System.out.print(y + " " + z);
} else {
System.out.print(z + " " + y);
}
} else if (y <= x && y <= z) {
System.out.print(y + " ");
if (x <= z) {
System.out.print(x + " " + z);
} else {
System.out.print(z + " " + x);
}
} else {
System.out.print(z + " ");
if (x <= y) {
System.out.print(x + " " + y);
} else {
System.out.print(y + " " + x);
}
}
}
}
优缺点
-
优点:
- 直接比较,简单直观,易于理解和实现。
-
缺点:
- 代码较长,存在大量重复的比较和输出逻辑。
方法二:使用数组排序
解题思路
- 将输入的x、y、z存放到数组中,使用排序算法对数组进行排序,然后输出排序后的结果。
代码
import java.util.Arrays;
import java.util.Scanner;
public class SortNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter number " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
Arrays.sort(numbers);
System.out.print("Sorted numbers: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
优缺点
-
优点:
- 使用数组和排序算法,简化了代码逻辑。
-
缺点:
- 需要额外的数组空间,增加了空间复杂度。
方法三:使用集合类
解题思路
- 将输入的x、y、z放入集合,集合类会自动进行排序,然后输出排序后的结果。
代码
import java.util.Scanner;
import java.util.TreeSet;
public class SortNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TreeSet<Integer> numbers = new TreeSet<>();
for (int i = 0; i < 3; i++) {
System.out.print("Enter number " + (i + 1) + ": ");
numbers.add(scanner.nextInt());
}
System.out.print("Sorted numbers: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
优缺点
-
优点:
- 使用了集合类,自动进行排序,简化了代码逻辑。
-
缺点:
- 需要额外的集合空间,增加了空间复杂度。
总结与推荐
- 三种方法都能解决问题,方法二和方法三使用了数组和集合,简化了代码逻辑,提高了代码的可维护性。
- 推荐方法二,因为它使用了数组和排序,简化了代码逻辑,提高了代码的可维护性。如果需要兼容旧版本的Java或有特殊要求,可以考虑方法一。如果要求保持排序后的顺序唯一性,可以考虑方法三。