0

我必须从文件中读取,然后将找到的单词放入 ArrayList 中。

public boolean load(String filename)
{

    try
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("wordlist.txt")));
        String line = null;
        while ((line = br.readLine()) != null)
        {
            String[] values = line.split("\n");
            wordlist.add(new WordPair(answer, question));
        }
    } catch (IOException ioe)
    {
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ioe);
    }

    return false;
}

以下是我使用的测试器代码:

public void testLoad() {
    assertTrue(wordPairDemo.save(fileName));    
    wordPairDemo.clear();                       
    assertTrue(wordPairDemo.load(fileName));
    assertTrue(wordPairDemo.size() == 3);
    assertEquals(wordPairDemo.lookup("hest"),"horse");
    assertEquals(wordPairDemo.lookup("hus"), "house");
    assertEquals(wordPairDemo.lookup("båd"),"boat");
}

我得到了 junit.Framework.AssertionFailedError,但我不确定是什么原因造成的。我已经尝试了几种不同类型的方法,通过扫描仪等,但我总是得到这个错误,我不知道该怎么处理它。

任何帮助表示赞赏!:)

4

1 回答 1

0

根据下面评论中的示例,该文件包含单行对: horse,hesthouse,husboat,båd

您应该根据您使用的实际分隔符进行拆分 - ,。例如:

public boolean load(String filename)
{
    try
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("wordlist.txt")));
        String line = null;

        // I'm leaving this loop under the assumption that there may be multiple lines
        while ((line = br.readLine()) != null) 
        {
            String[] values = line.split(",");
            for (int i = 0; i < line.lenght() / 2; ++i) {
                wordlist.add(new WordPair(values[i], values[i + 1));
            }
        }
    } catch (IOException ioe)
    {
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ioe);
    }

    return false;
}
于 2013-11-08T11:18:13.937 回答