【问题标题】:using an array list and getting an error使用数组列表并出现错误
【发布时间】:2017-02-22 00:02:22
【问题描述】:

这是我的代码,我似乎无法让差异方法正常工作当我尝试查看是否 !other.contains(set) 时出现错误,当我在检查它是否包含后尝试添加它时同样出现错误它。不知道我需要做什么来修复它,但如果有人可以提供帮助,那就太好了。

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


public boolean add(String word)
{

boolean x = true;
    if (word == null || word == "")
    {
        x = false;
    } else
    {
        if (word.length() > 0)
        {
            set.add(word);
            x = true;
            size++;
        }
    }
    return x;
}

public boolean contains(String word)
{

    boolean contains = false;
    if (word != null)
        contains = set.contains(word);
    return contains;
}


 /**
 * WordSet - This method should return a WordSet containing the words that
 *are in the current set but not in the other set (this – other).
 * 
 * @param other
 * @return WordSet
 */

public WordSet difference(WordSet other)
{
    WordSet differenceSet = new WordSet();
    boolean x = false;
    if (other != null)
        for (String str : set)
            if (!other.contains(set))
                differenceSet.add(set);
            return differenceSet;
}

【问题讨论】:

  • 其他到底是什么?
  • 您的意思是在这些语句中使用str 而不是set
  • 您的 difference() 方法在 iffor 语句周围没有大括号。在 Java 中,IMO 应始终为 if 语句块使用大括号,无论行数如何。 for 块肯定需要大括号。那,您正在检查其他是否包含set 而不是@4castle 提到的str
  • @Cyntech 它不需要它们——它是有效的代码。问题就像@4castle 说的,他添加的是set 而不是str
  • @JavaDevil 是的,你是对的,但是对于for 语句,如果他想要return 语句in for 循环,他需要大括号。

标签: java arrays list arraylist compiler-errors


【解决方案1】:

您需要检查 null 条件。
if (null != other.contains(set) && !other.contains(set)){ //your code here }

或者我想你可能想检查 str 而不是 _set_the 只需在 contains() 中替换它

if (word != null) contains = set.contains(word); return contains; // -> this will return null if contains is null which is causing the second error
在此处应用类似的补丁

if (word != null) {
if(null != set.contains(word) { contains = set.contains(word);
}
}
return contains;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多