使用程序为用户所录入的3 个数值进行升序排列,并将排序后的结果输出到控制台。(4种方法)
package day03;
//编写三个数值的排列顺序
import java.util.Scanner;
public class Sort {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请依次输入三个整数:a,b,c(以空格隔开)");
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
System.out.println("您输入的是:"+'\r'+"a="+a+",b="+b+",c="+c);
//方法一,复杂
if(a>b) {
if(b>c) {
System.out.println("升序排序后,结果为:"+'\r'+"c="+c+",b="+b+",a="+a);
}else {
System.out.println("升序排序后,结果为:"+'\r'+"b="+b+",c="+c+",a="+a);
}
}else {
if(b>c) {
if(a>c) {
System.out.println("升序排序后,结果为:"+'\r'+"c="+c+",a="+a+",b="+b);
}else {
System.out.println("升序排序后,结果为:"+'\r'+"a="+a+",c="+c+",b="+b);
}
}else {
System.out.println("升序排序后,结果为:"+'\r'+"a="+a+",b="+b+",c="+c);
}
}
//方法二
int max = 0;
int mid = 0;
int min = 0;
if (a>b && a>c) {
max = a;
}else if(b>a && b>c) {
max = b;
}else {
max = c;
}
if (a<b && a<c) {
min = a;
}else if(b<a && b<c) {
min = b;
}else {
min = c;
}
if((a>b && a<c) || (a>c && a<b)) {
mid = a;
}else if((b>a && b<c)|| (b>c && b<a)) {
mid = b;
}else {
mid = c;
}
System.out.println(min+" "+mid+" "+max);
//方法三
if(a>b) {
if(c>a) {
System.out.println("升序排序后,结果为:"+'\r'+"b="+b+",a="+a+",c="+c);
}else if(c<b) {
System.out.println("升序排序后,结果为:"+'\r'+"c="+c+",b="+b+",a="+a);
}else {
System.out.println("升序排序后,结果为:"+'\r'+"b="+b+",c="+c+",a="+a);
}
}else {
if(c<a) {
System.out.println("升序排序后,结果为:"+'\r'+"c="+c+",a="+a+",b="+b);
}else if (c>b) {
System.out.println("升序排序后,结果为:"+'\r'+"a="+a+",b="+b+",c="+c);
}else {
System.out.println("升序排序后,结果为:"+'\r'+"a="+a+",c="+c+",b="+b);
}
}
//方法四
if(a>b) {
int t = a;
a = b;
b = t;
}
if(a>c) {
int t = a;
a = c;
c = t;
}
if(b>c) {
int t = b;
b = c;
c = t;
}
System.out.println("升序排序后,结果为:"+'\r'+"a="+a+",b="+b+",c="+c);
}
}