这是我的代码,我似乎无法让差异方法正常工作当我尝试查看是否!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;
}
答案 0 :(得分:0)
您需要检查 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;
答案 1 :(得分:-1)
你的问题不是很清楚 但我想下面是你的代码的问题。
public WordSet difference(WordSet other)
{
WordSet differenceSet = new WordSet();
boolean x = false;
if (other != null)
for (String str : set)
{
if (!other.contains(str)) // You need to match with string in the set not the set.
differenceSet.add(set);
}
return differenceSet;
}