2014-05-18 3 views
1

에 요소를 추가하는 데 :어려움 나는 다음과 같다 .txt 파일이 2 차원 배열

Mathematics:MTH105 
Science:SCI205 
Computer Science:CPS301 
... 

을 그리고 내가 파일을 읽고 배열로 각 선을 배치해야 할당이를이해야 다음과 같이 : 내가 컴파일 오류를 얻고있다

subjectsArray[][] = { 
    {"Mathematics", "MTH105"}, 
    {"Science", "SCI205"}, 
    {"Computer Science", "CPS301"} 
}; 

을 나는 2 차원 배열에 파일의 내용을 추가 할 때 :

private static String[][] getFileContents(File file) { 

    Scanner scanner = null; 
    ArrayList<String[][]> subjectsArray = new ArrayList<String[][]>(); 

    //Place the contents of the file in an array and return the array 
    try { 
     scanner = new Scanner(file); 
     int i = 0; 

     while(scanner.hasNextLine()) { 

      String line = scanner.nextLine(); 
      String[] lineSplit = line.split(":"); 

      for(int j = 0; j < lineSplit.length; j++) { 
       subjectsArray[i][j].add(lineSplit[0]); //The type of the expression must be an array type but it resolved to ArrayList<String[][]> 
      } 

      i++; 
     } 
     return subjectsArray; 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } finally { 
     scanner.close(); 
    } 
    return null; 
} 

오류가 읽

The type of the expression must be an array type but it resolved to ArrayList<String[][]> 

는 나는 내가 잘못이 무엇인지를 여러 차원 배열 새로운 모르겠습니다. 누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까?

+1

코드에서 오류에 관해 질문 할 때 전체 오류 메시지를 게시하고 코드에 표시하는 것이 현명하고 도움이됩니다. 어느 선이 그것을 일으키는 지. 이 정보를 포함시켜야한다는 것이 분명한 것 같습니다. –

+1

@HovercraftFullOfEels 예 : subjectsArray [i] [j] .add (lineSplit [0]); // 표현식 유형은 배열 유형이어야하지만 ArrayList로 해석되어야합니다.

+1

@NicholasLaw 독자가 코드를 찾을 필요가 없도록 코드 외부에 두는 것이 좋습니다. – awksp

답변

2

첫 번째 실수는 결과에 대한 유형의 선택입니다 :

ArrayList<String[][]> 

3 차원 구조를 나타내는 이러한 유형 - 2 차원 배열의 목록을 표시합니다. 필요한 것은 2 차원 구조입니다.

ArrayList<String[]> 

은 그래서 첫 번째 수정은 이것이다 :이 완료되면

List<String[]> subjectsArray = new ArrayList<String[]>(); // Note the type on the left: it's an interface 

, 나머지 코드는 그 자체로 흐름 : 당신이 내부 for 루프가 필요하지 않습니다, 그것은 하나의로 대체됩니다 라인 :

subjectsArray.add(lineSplit); 

최종 수정은 return 라인 : 당신이를 호출하여 수행 할 수있는 List<String[]>-String[][]을 변환해야, 다음과 같이하십시오 :

return subjectsArray.toArray(new String[subjectsArray.size()][]); 
+0

'toArray()'는 요소가'String []'인'Object []'를 반환하지 않겠습니까? – awksp

+1

@ user3580294 맞습니다. 결과 배열을 넣어야합니다. 감사! – dasblinkenlight

+0

@ dasblinkenlight 귀하의 도움에 감사드립니다. 이 ArrayList contentsArray = new ArrayList ();'로 변경했지만 제안 된 오류가 발생했습니다. 형식 불일치 : ArrayList 을 ArrayList '으로 변환 할 수 없습니다. 도울 수 있니? –

0

여러분은 String에 ArrayList 메소드를 사용하려고합니다. 나는 그것이 가능하다는 것을 확신하지 못한다. 당신이 필요로하는 것을 수행하는 가장 간단한 방법은 다음과 같습니다.

for(int j = 0; j < lineSplit.length; j++) { 
      subjectsArray[i][j]=lineSplit[j]; 
     }