2016-11-18 3 views
4

String (특정 이름 임) 입력을 얻으려는 경우 해당 셀에 대해 크기가 26 인 Array에 저장하십시오. 정렬 방식은 다음과 같습니다. 'A'로 시작하는 이름은 셀 0으로 이동하고 'B'로 시작하는 이름은 셀 1로 이동합니다. 이제 셀에는 LinkedList이 포함되어 있으며 이름은 알파벳순으로 다시 정렬됩니다.이름을 정렬하고 LinkedList를 사용하여 배열 셀에 저장

지금까지 만들어진 방법은 스위치 케이스를 사용하는 것입니다.

private void addDataAList(AuthorList[] aL, String iN) { 
    char nD = Character.toUpperCase(iN.charAt(0)); 
     switch(nD){ 
      case 'A': 
       AuthorList[0] = iN; 
      break; 

      case 'B': 
       AuthorList[1] = iN; 
      break; 
      //and so on 
     } 
}//addData 

더 효율적인 방법은 무엇입니까?

+5

가지고

private class AuthorList{ private LinkedList<String> nameList; public AuthorList() { } public AuthorList(LinkedList<String> nameList) { this.nameList = nameList; } public LinkedList<String> getNameList() { return nameList; } public void setNameList(LinkedList<String> nameList) { this.nameList = nameList; } @Override public String toString() { final StringBuilder sb = new StringBuilder("AuthorList{"); sb.append("nameList=").append(nameList); sb.append('}'); return sb.toString(); } } 

내가 이런 식으로 만들 것 당신은'AuthorList [nD - 'A'] = iN;'시도 했습니까? – OldCurmudgeon

+0

@OldCurmudgeon 아니요. 고맙습니다. 나는 네가 이렇게 할 수 있을지조차 몰랐다. – Helquin

+0

하지만 어떻게 든 ArrayOutOfBoundException으로부터 보호해야합니다. 예를 들어 그것을 잡아서 대문자 첫 글자의 요구 사항에 대한 적절한 메시지와 함께 새로운 IllegalArgumentException을 던져라. 또한 iN.trim()이 유용 할 수 있습니다. –

답변

1

그 AuthorList 클래스를 가정하면 다음과 같이 보일 수 있습니다 : 테스트 용

private static void addDataAList(AuthorList[] aL, String iN) { 
    int index = Character.toUpperCase(iN.trim().charAt(0)) - 'A'; 
    try { 
     AuthorList tmpAuthorList = aL[index]; 
     if(tmpAuthorList == null) aL[index] = tmpAuthorList = new AuthorList(new LinkedList<>()); 
     if(tmpAuthorList.getNameList() == null) tmpAuthorList.setNameList(new LinkedList<>()); 
     tmpAuthorList.getNameList().add(iN); 
    } catch (ArrayIndexOutOfBoundsException aioobe){ 
     throw new IllegalArgumentException("Name should start with character A - Z"); 
    } 
} 

그리고 추가의 주요 방법 :

public static void main (String[] args){ 
    AuthorList[] aL = new AuthorList[26]; 
    addDataAList(aL, " dudeman"); 
    for (AuthorList list : aL) System.out.println(list); 
} 
+0

리스트가 일반 iirc가 아니거나 ArrayList로되어있는 것입니까? 어느 쪽이든, 나는 당신의 코드를 모델화하려고 시도하고 이것이 대답으로 받아 들여지기 전에 그것이 작동 하는지를 볼 것입니다. – Helquin

+0

필자는 AuthorList가 무엇인지, 데이터를 추가하는 방법을 모르지만 '='AuthorList [x]에 String을 할당하면 실패 할 것이므로 테스트 목적으로 제대로 작동하도록 변경했습니다. 물론 AuthorList 클래스를 사용하여이 솔루션을 사용자 요구에 맞춰야합니다. –