我寫了一個程序,要求用戶輸入名稱到數組中,然後名稱按字母順序排序......該程序運行良好,但我想知道是否可以對由第二,第三,或每個字符串中的第4個字符?例如,如果用戶輸入了Bob,Dan和Kris,程序應該將它們排序爲Dan,Bob,Kris。這是我的計劃,由字符串的第一個字母排序我的字符串數組:如何通過每個字符串的第二個字符串來排序字符串數組?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SortingAnArrayOfStrings {
public static void main(String[] args) {
{
//Ask the user for names to add to the array
List<String> list=new ArrayList<String>();
Scanner in=new Scanner(System.in);
do {
System.out.println(" The names on the list are "+list);
System.out.println("Would you like to add another name to the list? (y/n)");
if (in.next().startsWith("y")) {
System.out.println("Enter:");
list.add(in.next());
}else{break;
}
} while (true);
//display the names that have been added to the array
System.out.println("The names on the list are "+list);
//sort the array of names in alphabetical order
String[] Arr=list.toArray(new String[list.size()]);
String[] stringArray=new String[Arr.length];
for(int i=0;i<Arr.length;i++)
{
for (int j = i+1; j < Arr.length; j++) {
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
String temp=Arr[j];
Arr[j]=Arr[i];
Arr[i]=temp;
}
}
stringArray[i]=Arr[i];
}
//display the sorted list of names
System.out.println("This is the list of names after sorting them in alphabetical order : ");
for(String ss:stringArray){
System.out.print(ss + " ");
}
}
}
}
謝謝。這非常有幫助,但可以在不使用比較器的情況下編寫程序嗎? – pikProgram
@pikProgram - 你可以用''for''循環進行手動解析,但有機會犯錯,代碼看起來很冗長,很難閱讀。所以我們應該使用java功能來利用語言。 – mmuzahid
我明白了......謝謝...... – pikProgram