亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從文本文件創建的字典 - contains() 總是返回 false

從文本文件創建的字典 - contains() 總是返回 false

藍山帝景 2021-11-03 09:57:51
我目前正忙于一項小型大學作業,并且在使用我實現的字典類的 contains() 方法時遇到了一些問題 - 該方法總是返回 false。這個類看起來像這樣:public class LocalDictionary {    private ArrayList<String> wordsSet;    public LocalDictionary() throws IOException {        String wordListContents = new String(Files.readAllBytes(Paths.get("words.txt")));        wordsSet = new ArrayList<>();        String[] words = wordListContents.split("\n");        for (int i = 0; i < words.length; i++) {            wordsSet.add(words[i].toLowerCase());        }    }    public boolean contains(String word) {        return wordsSet.contains(word.toLowerCase());    }}字典從中獲取單詞的“words.txt”文件可在https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt獲得,但這里是它的外觀片段:zinkedzinkenitezinkyzinkiferouszinkifyzinkifiedzinkifieszinkifyingzinniazinniaszinnwalditezinoberzinsangzinzarzinziberaceae我已經確保“words.txt”中的單詞包含在“wordsSet”中,但無法弄清楚為什么 contains 方法對于似乎在 ArrayList 中的單詞返回 false。非常感謝任何幫助。
查看完整描述

2 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

嘗試BufferedReader,我嘗試并為我工作(我刪除了一些無用的行)。在您的使用中,您從文件中讀取所有字節,會有額外的字節。


public class LocalDictionary {

    private ArrayList<String> wordsSet = new ArrayList<>();


    public LocalDictionary() throws Exception {


        //dont forget to absolute path to here. click righ click to file and copy path

        File file = new File("C:\\Users\\higuys\\IdeaProjects\\try\\src\\words.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));


        String line;

        while ((line = br.readLine()) != null)

            //trim and tolowercase and add to list.

            wordsSet.add(line.trim().toLowerCase());


    }


    public boolean contains(String word) {

        return wordsSet.contains(word.toLowerCase());

    }

}


查看完整回答
反對 回復 2021-11-03
?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

嘗試BufferedReader,我嘗試并為我工作(我刪除了一些無用的行)。在您的使用中,您從文件中讀取所有字節,會有額外的字節。


public class LocalDictionary {

    private ArrayList<String> wordsSet = new ArrayList<>();


    public LocalDictionary() throws Exception {


        //dont forget to absolute path to here. click righ click to file and copy path

        File file = new File("C:\\Users\\higuys\\IdeaProjects\\try\\src\\words.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));


        String line;

        while ((line = br.readLine()) != null)

            //trim and tolowercase and add to list.

            wordsSet.add(line.trim().toLowerCase());


    }


    public boolean contains(String word) {

        return wordsSet.contains(word.toLowerCase());

    }

}


查看完整回答
反對 回復 2021-11-03
  • 2 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號