程序分析
方法1:定义数组存储数据
此方法较为简便,排序处理只需调用数组工具(Arrays
)中的sort()
方法即可。
private static void method1() {
int[] nums = new int[3];
System.out.println("请输入三个数据:");
for (int i = 0; i < nums.length; i++) {
nums[i] = input.nextInt();
}
Arrays.sort(nums);//排序
System.out.println("按小到大输出:");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+",");
}
}
方法2:定义三个int型变量存储数据
private static void method2() {
System.out.println("请输入三个数据a,b,c:");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int item;
for (int i = 0; i < 3; i++) {
if (a > b){
item = a;
a = b;
b = item;
}
if (a > c){
item = a;
a = c;
c = item;
}
if (b > c){
item = b;
b = c;
c = item;
}
}
System.out.println("按小到大输出:");
System.out.println(a+","+b+","+c);
}
代码实现
import java.util.Arrays;
import java.util.Scanner;
/*34、输入3个数a,b,c,按大小顺序输出。*/
public class Test_33 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// method1();
method2();
}
private static void method1() {
int[] nums = new int[3];
System.out.println("请输入三个数据:");
for (int i = 0; i < nums.length; i++) {
nums[i] = input.nextInt();
}
Arrays.sort(nums);//排序
System.out.println("按小到大输出:");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+",");
}
}
private static void method2() {
System.out.println("请输入三个数据a,b,c:");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int item;
for (int i = 0; i < 3; i++) {
if (a > b){
item = a;
a = b;
b = item;
}
if (a > c){
item = a;
a = c;
c = item;
}
if (b > c){
item = b;
b = c;
c = item;
}
}
System.out.println("按小到大输出:");
System.out.println(a+","+b+","+c);
}
}