gpt4 book ai didi

java newbie : reading in a file for word search code. .add() 和 .toArray() 给我错误

转载 作者:行者123 更新时间:2023-12-01 23:41:46 25 4
gpt4 key购买 nike

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

}
}

最佳答案

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

相反,创建一个数组列表:

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

然后添加:

list.add(read.readLine());

完成后,使用列表调用 toArray。

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

关于java newbie : reading in a file for word search code. .add() 和 .toArray() 给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17797374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com