【发布时间】: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()方法在if或for语句周围没有大括号。在 Java 中,IMO 应始终为if语句块使用大括号,无论行数如何。for块肯定需要大括号。那,您正在检查其他是否包含set而不是@4castle 提到的str。 -
@Cyntech 它不需要它们——它是有效的代码。问题就像@4castle 说的,他添加的是
set而不是str -
@JavaDevil 是的,你是对的,但是对于
for语句,如果他想要return语句in for 循环,他需要大括号。
标签: java arrays list arraylist compiler-errors