0

我真的想弄清楚这段代码有什么问题。.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() {

    }
} 
4

2 回答 2

2

您正在调用add(BufferedReader,这是不可能的。

相反,创建一个 arrayList:

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

然后添加:

list.add(read.readLine());

然后在完成后使用列表调用 toArray。

我不打算使用 Word 类,因为我们处理的是文本行,而不是单词。

于 2013-07-22T21:07:12.200 回答
1

read是 a BufferedReader,它没有.add().toArray()方法。在此处查看文档:http: //docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html

也许您想将项目添加到数组或数组列表中。

于 2013-07-22T21:08:04.027 回答