Java 如何解决向文件传递参数时出现的未定义构造函数错误?
我在将一个文件作为参数从名为Java 如何解决向文件传递参数时出现的未定义构造函数错误?,java,file,Java,File,我在将一个文件作为参数从名为WordList的类传递到main类时遇到问题,而只是将单词的ArrayList打印到终端。调用构造函数时无法传递参数“Words”,因为“无法解析为变量”-错误。文件路径正常,我已经检查过了 单词列表类: public class WordList{ private List<String> wordlist = new ArrayList<>(); File Words = new File("task/words
WordList
的类传递到main类时遇到问题,而只是将单词的ArrayList
打印到终端。调用构造函数时无法传递参数“Words”,因为“无法解析为变量”-错误。文件路径正常,我已经检查过了
单词列表类:
public class WordList{
private List<String> wordlist = new ArrayList<>();
File Words = new File("task/words");
public WordList(File Words){
this.Words = Words;
}
//Returns the words in the file as list
public List<String> giveWords() throws IOException, FileNotFoundException{
BufferedReader reader = new BufferedReader(new FileReader(Words));
String line = reader.readLine();
while (line != null){
wordlist.add(line);
line = reader.readLine();
}
reader.close();
return wordlist;
}
}
更改此行(在类main
的方法main
中)
WordList-WordList=newwordlist();
对此
WordList-WordList=newwordlist(新文件(“任务/单词”);
当您调用类WordList
的构造函数时,必须提供一个文件
。其思想是类WordList
可以处理任何文件,而不仅仅是文件任务/单词
public class Main {
public static void main(String[] args){
WordList wordlist = new WordList(); // Error happens here
System.out.println(wordlist.giveWords());
}
}