Java 英文字母排序问题

2024-12-02 13:08:26
推荐回答(2个)
回答1:

public static void main(String[] args) {
// TODO Auto-generated method stub
Random ra = new Random();
System.out.println("排序前");
int a=0;
String[] array=new String[]{"a","b","c","d","e","f","g","h","i","j"};
String [] newArray=new String[10];
for(int i=0;i<10;i++){
a=ra.nextInt(9);
newArray[i]=array[a];
System.out.println(newArray[i]);
}
System.out.println("排序后");
Arrays.sort(newArray);
for (int i = 0; i < newArray.length; i++) {
System.out.println(newArray[i]);
}
}

回答2:

import java.util.*;

public class test {
public static void main(String[] args) {
Random r = new Random();
char[] a = new char[10];
for(int i = 0; i < 10; ++i) {
a[i] = (char)(r.nextInt(26)+65 + (r.nextInt(2) == 0 ? 0 : 32)); // 随机生成10个字母
}
for(int i = 0; i < 10; ++i) // 排序
for(int j = 9; j > i; --j)
if(a[j] < a[j-1]) {
char t = a[j];
a[j] = a[j-1];
a[j-1] = t;
}
System.out.println(new String(a));
}
}