문제
ArrayList가 설정되어 있습니다. 입력 인스턴트도 설정되어있어 사용자가 하나의 문자열, 하나의 정수, 하나의 문자열 (이름, 나이 및 성)을 입력 할 수 있습니다.
ArrayList를 성으로 정렬해야합니다. 지금까지 입력 한 코드는 모두 주요 방법에 따라 다릅니다.
public static void main(String[] args) {
Name Name[] = new Name[50];
int count = 0;
for (int i=0; i<50; i++)
NewName[i] = new Name();
//ADD NEW TO ARRAYLIST NAME
String FName = JOptionPane.showInputDialog("first name");
int age = Integer.parseInt(JOptionPane.showInputDialog("age"));
String LName = JOptionPane.showInputDialog("last name");
NewName[count] = new Name(FName, age, LName);
count = count++;
}
//ITEMS SORT BY LAST NAME
//CODE FOR SORT GOES HERE
해결책
보세요 유사한, 비교기, 배열 .SORT 그리고 Collections.SORT
import java.util.Arrays;
class Name implements Comparable<Name> {
private String lastName;
//Other fields
public Name(String lastName){
this.lastName = lastName;
}
public int compareTo(Name o) {
//Null checks etc
return lastName.compareTo(o.lastName);
}
public String getLastName(){
return lastName;
}
//Getter and setter methods
}
public class Test{
public static void main(String[] args) {
Name[] arr = new Name[]{new Name("AAC"), new Name("AAD"), new Name("AAA"),new Name("ABC"), new Name("AADDE")};
Arrays.sort(arr);
for(Name nm:arr){
System.out.println(nm.getLastName());
}
}
}
다른 팁
이것은 불쾌한 것이 아니지만 스윙으로 넘어 가기 전에 기본 사항을 배우는 것이 좋습니다.
제휴하지 않습니다 StackOverflow