【问题标题】:My add word to array if not in there already function is not working. What am I doing wrong?如果不在数组中,我的 add word 功能不起作用。我究竟做错了什么?
【发布时间】:2014-12-08 23:38:35
【问题描述】:

我有一个数组,正在从文本文件中读取一系列单词。我要做的是,如果扫描仪所在的当前单词不在数组中,则将其添加到数组中。如果该单词已经在数组中,则转到下一个单词并再次开始该过程 - 检查它是否在数组中,如果没有则添加它,依此类推。问题是我加载了一个单词 abc,它不在数组中,所以我添加了它。然后我加载另一个单词 x,它不在数组中,所以我添加它。然后我尝试再次加载 abc,它已经在数组中,但无论如何它都会被添加。我的代码需要更改哪些内容?

    try {
        fileScanner = new Scanner(inFile).useDelimiter("[ ,!?.0123456789]+");
        System.out.println("The input has been loaded successfully.");

        while (fileScanner.hasNext()) {
            currentWord = fileScanner.next().toUpperCase();

            // If the word is not found, add it to the array.
            if (ht.findWord(currentWord, ht.array) == false) {
                ht.fillTable(currentWord, ht.asciiSum(currentWord), ht.array);
            } else {
            // if the word is found, move on to the next word.
                break;
            }

        }
        fileScanner.close();
    } // end try
    catch (Exception e) {
        System.out.println("The input file has not been successfully loaded.");
    }



public boolean findWord(String word, String[] table) {
    boolean found = false;
    for (int i = 0; i < table.length; i++) {
        if (table[i] == word) {
            found = true;
            //System.out.println("The word " + word + " was found at " + table[i]);
        } else {
            found = false;
        }
    }
    return found;
}

【问题讨论】:

  • 比较两个字符串 table[i] == word 的错误方式。你必须使用 equals()

标签: java arrays search boolean lookup


【解决方案1】:

您的代码需要在findWord 方法中稍作更改:

public boolean findWord(String word, String[] table) {
    for(int i = 0; i < table.length; i++) {
        if (table[i].equals(word)) {
            //this line is necessary because otherwise your loop
            //will continue setting found to false if there are
            //any other words in the array
            return true;
        }
    }
    return false;
}

【讨论】:

    【解决方案2】:

    当你想比较两个字符串时,你必须使用equals()函数

    公共布尔等于(Object anObject)

    将此字符串与指定对象进行比较。结果为真,如果 并且仅当参数不为 null 并且是一个 String 对象时 表示与此对象相同的字符序列。

    if (table[i] == word) {
    

    改成

    if (table[i].equals(word)) {
    

    因此,findWord(String word, String[] table) { 不仅仅返回 false

    另一点

     if (ht.findWord(currentWord, ht.array) == false) {
    

    相等

    if (!ht.findWord(currentWord, ht.array)) {
    

    【讨论】:

    • 感谢您提供所有这些信息。这很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 2019-05-26
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多