我从键盘上获取一个关于英文水果名字的数组,想让它输出这样的顺序,如:
第1种水果:bnch
第2种水果:drt
第3种水果:awf
第4种水果:efb
第5种水果:cty输出结果:
这些水果在字典中的排列顺序是:
awf
bnch
cty
drt
efb
就是首字母还按照字典排序排序
第1种水果:bnch
第2种水果:drt
第3种水果:awf
第4种水果:efb
第5种水果:cty输出结果:
这些水果在字典中的排列顺序是:
awf
bnch
cty
drt
efb
就是首字母还按照字典排序排序
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/*String a = "abvssds";
String b = "aawdasdsa";
System.out.println(b.compareToIgnoreCase(a));
*/
String[] a = {"bnch","drt","drt","awf","efb","cty"};
sort(a);
for(int i =0 ;i<a.length;i++) {
System.out.println(a[i]);
}
}
public static void sort(String[] a) {
int length = a.length;
for(int i=0;i<length;i++) {
for(int j=i+1;j<length;j++) {
if(a[i].compareToIgnoreCase(a[j]) > 0) {
String b = a[i];
a[i] = a[j];
a[j] = b;
}
}
}
if(str[0].compareTo(str[1])>0) //两字符串比较
{temp=str[0];
str[0]=str[1];
str[1]=temp;用方法排序就是 了
import java.util.*;
public class Test {
public static void main(String args[]) throws Exception {
String[] a = {"bnch","drt","drt","awf","efb","cty"};
Arrays.sort(a);
for(int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
}
}直接用Array.sort()排序就行了
Array类中有排序的方法
Arrays.sort(a);
for(int i = 0;i < a.length; i ++){
System.out.println(a[i]);
}