【发布时间】:2022-02-03 00:04:34
【问题描述】:
我需要一个只打印数组的唯一元素的程序,或者,如果没有唯一元素,它会打印“Null”。 我的代码已经可以找到唯一的元素并打印它,但它也为每个重复的元素打印 Null。如果没有唯一数字或只有唯一元素(已经为此工作),我只需要打印一个“Null”。 下面的例子,它应该打印 3(不重复的元素),如果你在列表中放另一个 3,应该只打印一次 Null(我不知道怎么做)。 提前感谢您的帮助!
public static void main(String[] args) {
int IDs[] = { 1, 2, 3, 2, 2, 1, 5, 5 };
int items = IDs.length;
uniqueIDs(IDs, items);
}
static void uniqueIDs(int IDs[], int items) {
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < items; i++) {
if (hash.containsKey(IDs[i])) {
hash.put(IDs[i], hash.get(IDs[i]) + 1);
}
else {
hash.put(IDs[i], 1);
}
}
for (Map.Entry<Integer, Integer> uniqueIDs : hash.entrySet())
if (uniqueIDs.getValue() == 1)
System.out.print(uniqueIDs.getKey() + "\n");
else {
System.out.println("null");
}
}
}
【问题讨论】:
标签: java arrays arraylist hash hashmap