我真的想弄清楚这段代码有什么问题。 .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() {
}
}
答案 0 :(得分:2)
你在BufferedReader上调用add(
,这是不可能的。
而是创建一个arrayList:
ArrayList<String> list=new ArrayList<>();
然后添加:
list.add(read.readLine());
完成后,用列表调用toArray。
我不会使用Word类,因为我们正在处理文本行,而不是单词。
答案 1 :(得分:1)
read
是BufferedReader
,没有.add()
和.toArray()
方法。在这里查看文档:{{3}}
也许你想把这些项目添加到一个数组或一个arraylist中。