import java.util.Arrays;
import java.util.Scanner;
public class Demo6 {
/**
* 案例:我有如下一个字符串:”91 27 46 38 50”,请写代码实现最终输出结果是:”27 38 46 50 91”
加强版:
数据不再是写死的了,让用户键盘录入,当用户输入exit的时候,结束录入,然后来排序。
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数组(结束时输入exit):");
StringBuffer sb1 = new StringBuffer();
for (int i = 1 ; ;i++ ) {
System.out.println("请输入第"+i+"个元素:");
String str = sc.nextLine();
if (!str.equalsIgnoreCase("exit")) {
sb1.append(str).append(" ");
}else {
System.out.println("输入结束。");
break;
}
}
//String st = sc.nextLine();
//StringBuffer sbs = new StringBuffer();
//String str = sbs.substring(st.length()-5, st.length()-1);
//String str = sb1;
String str = sb1.substring(0, sb1.length());
//输入一个字符串
//String str = "12 36 45 20 35 45 87 90 59 24";
//切割字符串
String[] arr = str.split(" ");
//定义一个数组,
int[] ar = new int[arr.length];
for (int i = 0; i < ar.length; i++) {
ar[i] = Integer.parseInt(arr[i]);
}
Arrays.sort(ar);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ar.length; i++) {
if(i == ar.length - 1) {
sb.append(ar[i]);
}else {
sb.append(ar[i] + " ");
}
}
System.out.println(sb);
}
} |
|