嘗試使用比較排序您的輸入。爲了簡單起見,我刪除了您的參數相關的代碼。您仍然需要重新正確添加它。
所需導入
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
的名稱
class Name{
public static final String FULL_NAME_DELIMITER = " ";
public static final String PRINT_DELIMITER = ", ";
private String firstName;
private String lastName;
public Name(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public static String[] getName(String fullName){
return fullName.split(FULL_NAME_DELIMITER);
}
public String getLastName(){
return this.lastName;
}
@Override
public String toString(){
return String.join(PRINT_DELIMITER , this.lastName, this.firstName);
}
public void print(){
System.out.println(this);
}
}
的比較
class NameComparator implements Comparator<Name>{
@Override
public int compare(Name a, Name b) {
return a.getLastName().compareTo(b.getLastName()); // ASC: a to b or DESC: b to a
}
}
使用
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The input names
String[] input = new String[]{
"john main",
"rob class",
"bob ram"
};
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
編輯
要在命令行中使用的輸入,在ARGS參數是要使用的東西。
與命令行輸入使用
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The method (in case something else than "sort" is desired)
String method = args[0];
// Check for valid method
if(!method.equals("sort")) return;
// The input names
String[] input = Arrays.copyOfRange(args, 1, args.length);
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
EDIT 2
要使用的第一個名字,而不是姓氏,只是改變比較。
class NameComparator implements Comparator<Name>{
@Override
public int compare(Name a, Name b) {
return a.getFirstName().compareTo(b.getFirstName()); // ASC: a to b or DESC: b to a
}
}
當然,你需要調整名稱類以及通過增加:
public String getFirstName(){
return this.firstName;
}
哪裏是你的輸入來的呢?什麼是'args_name'?什麼是'名字'?顯示整個代碼。此代碼不能編譯。 – nhouser9
你會給CMD名單嗎? –
如果您正在讀取要從命令行排序的名稱,那麼您如何區分名字和姓氏? –