输入三个字符串,按由小到大的顺序输出 字符串排序-一种简单的方法
1 /** 2 * 对两位数的ascii是可以的 3 * 对三位数的就不行了 4 */ 5 import java.util.Scanner; 6 public class 字符串排序 { 7 8 public static int getMax(int x, int y) { 9 return x>y?x:y; 10 } 11 public static int getMin(int x, int y) { 12 return x<y?x:y; 13 } 14 public static int GetMiddle(int x,int y,int z) { 15 int temp=0; 16 if(x>y) 17 { 18 temp=x; 19 x=y; 20 y=temp; 21 } 22 if(z<x) return x; 23 else if(z<y) return z; 24 else return y; 25 } 26 27 public static void main(String[] args) { 28 Scanner scanner=new Scanner(System.in); 29 String str1=scanner.next(); 30 String str2=scanner.next(); 31 String str3=scanner.next(); 32 int[] str1_num =new int[3]; 33 int[] str2_num =new int[3]; 34 int[] str3_num =new int[3]; 35 for(int i=0;i<3;i++) { 36 str1_num[i]=Integer.valueOf(str1.charAt(i)); 37 str2_num[i]=Integer.valueOf(str2.charAt(i)); 38 str3_num[i]=Integer.valueOf(str3.charAt(i)); 39 } 40 int n1=str1_num[0]*10000+str1_num[1]*100+str1_num[2]; 41 int n2=str2_num[0]*10000+str2_num[1]*100+str2_num[2]; 42 int n3=str3_num[0]*10000+str3_num[1]*100+str3_num[2]; 43 int max=getMax(n1, getMax(n2, n3)); 44 int middle=GetMiddle(n1, n2, n3); 45 int min=getMin(n1, getMin(n2, n3)); 46 47 System.out.print((char)(min/10000)); 48 System.out.print((char)(min%10000/100)); 49 System.out.print((char)(min%10000%100)); 50 System.out.print(min); 51 System.out.print((min/10000)); 52 System.out.print((min%10000/100)); 53 System.out.print((min%10000%100)); 54 System.out.println(); 55 System.out.print((char)(middle/10000)); 56 System.out.print((char)(middle%10000/100)); 57 System.out.print((char)(middle%10000%100)); 58 System.out.println(); 59 System.out.print((char)(max/10000)); 60 System.out.print((char)(max%10000/100)); 61 System.out.print((char)(max%10000%100)); 62 63 64 } 65 66 }
控制变量,逐步交换相邻的两个,直到确定最终顺序
1 import java.util.Scanner; 2 public class 字符串排序第二种方法 { 3 4 public static void main(String[] args) { 5 6 Scanner scanner =new Scanner(System.in); 7 String str1=scanner.next(); 8 String str2=scanner.next(); 9 String str3=scanner.next(); 10 if(str1.compareTo(str2)>0) { 11 String temp=str1; 12 str1=str2; 13 str2=temp; 14 } 15 if(str1.compareTo(str3)>0) { 16 String temp=str1; 17 str1=str3; 18 str3=temp; 19 } 20 if(str2.compareTo(str3)>0) { 21 String temp=str3; 22 str3=str2; 23 str2=temp; 24 } 25 System.out.println(str1); 26 System.out.println(str2); 27 System.out.println(str3); 28 //System.out.println(str1+str2+str3); 29 scanner.close(); 30 } 31 32 }
万事走心 精益求美