2013-07-22 3 views
0

나는이 코드가 무엇이 잘못되었는지 알아 내려고 정말로 노력하고있다. .add() 및 .toArray()에는 그 아래에 빨간색 선이 있습니다. 이 두 줄을 쓰는 것에 대한 대안이 있습니까? 내가 도대체 ​​뭘 잘못하고있는 겁니까?자바 초보자 : 단어 검색 코드로 파일을 읽는 중. .add()와 .toArray()가 에러를 내고있다.

package prog3; 

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.*; 

public class WordList { 

    private String filename; 
    private Word[] words; 

    public WordList(String fileName) { 
     this.filename = fileName; 
    } 

    //reads in list of words and stores them internally. line by line 
    //if method reas list of words successfully, then it returns as true, otherwise false 

    public boolean readFile() { 

     try{ 
      BufferedReader read; 
      read = new BufferedReader(new FileReader(filename)); 
      String nextLine; 
      while ((nextLine = read.readLine())!= null) { 
       nextLine = nextLine.trim(); 
       read.add(new Word(nextLine)); 
      } 

      words = read.toArray(new Word[0]); 
     }catch(IOException ex){ 
      System.out.println("Caught exception: " +ex.getMessage()); 
      return false; 
     } 
     return true; 
    } 

//getList is supposed to return the list of words as an array of class Word. How do I do this??? 

public Word[] getList() { 

    } 
} 
+1

빨간 선 위에 마우스를 올려 놓았을 때 나타나는 오류는 무엇입니까? – hexafraction

+0

기호 심볼을 찾을 수 없습니다. 메서드 toArray (Word [])) 위치 : BufferedReader 유형의 변수 읽기 – DanielleElizabeth

+1

버퍼링 된 판독기가 아닌 ArrayList에 'add (')를 호출해야합니다 – hexafraction

답변

2

당신은 BufferedReader에 add(을 호출하고 있습니다. 불가능합니다.

대신, ArrayList를 만들기 :

ArrayList<String> list=new ArrayList<>(); 

그런 다음에 추가 할 때

list.add(read.readLine()); 

그런 다음 목록 toArray를 호출합니다.

우리는 단어가 아닌 텍스트 줄을 사용하므로 Word 클래스를 사용하지 않을 것입니다.

+0

코드의 의미는 – DanielleElizabeth

+0

입니다. 'list.toArray (새 단어 [0])'입니까? – DanielleElizabeth

+0

아니요, String 객체의 배열이 있습니다. 우리는 한 줄씩 읽는 것처럼 단어를 다루지 않습니다. – hexafraction

1

readBufferedReader이며, 이는 .add().toArray() 방법을 갖지 않는다. 여기에 문서를 확인하십시오 : http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html

아마 배열이나 arraylist에 항목을 추가하고 싶습니다.

+0

오류가 발생하는 줄을 제거하고 list.add (read.readLine());를 추가했습니다. 하지만 완료되면 목록과 함께 toArray를 어떻게 호출해야합니까? – DanielleElizabeth

+0

'list'라는 ArrayList가 있다면'list.toArray()'라고 말하면 ArrayList가 배열로 변환됩니다. 다시 한 번, 설명서를 살펴 보는 것이 좋습니다. http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html –