尝试使用递归来添加arraylist中的文件中的单词

时间:2016-09-23 16:03:48

标签: java recursion arraylist methods

我已经用java编写了一段时间,现在我正在帮助一位开始上学的朋友。在帮助他的同时,我编写了一个ArrayList方法来添加文件中的单词并将其存储在ArrayList中。现在我已经制作了这个方法,我试着想出一种递归的方式来编写相同的方法。目前的方法如下:

public Lexicon(String filename) throws IOException{
    wordlist = new ArrayList<>();

    Scanner scanWord = new Scanner(new File(filename));
    while (scanWord.hasNextLine()){
        wordlist.add(scanWord.nextLine());
        wordCount++;
    }
    scanWord.close();

}

1 个答案:

答案 0 :(得分:1)

不知道你为什么要做这样的事情,但是我假设你只是做一个自我调用的方法,直到没有剩下的行。

public Lexicon(String filename) throws IOException{
....

    public void addWord(Scanner scanWord, List<> wordLst) {
        if (scanWord.hasNextLine()) {
            wordLst.add(scanWord.nextLine());
            addWord(scanWord, wordLst);
        } else {
            // base case - no more words
        }
    }
...
}