I need a program that prints only the unique elements of an Array, OR, if there are no unique elements, it prints "Null". My code already can find the unique elements and print it, but it's printing Null for each repeated ones too. I need to print just one "Null" if there are no unique numbers, or just the unique elements (which is working already for that). The example below, it should print 3 (the non repeated element), and if you put another 3 in the list, should print Null one time only (which I can't figure out how). I appreciate the help in advance!
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");
}
}
}
CodePudding user response:
After the first loop in your method you should add this:
public static void main(String[] args) {
int IDs[] = {1, 2, 3, 2, 2, 1, 5, 3, 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);
}
}
boolean flag = false; //We assume we don't have unique elements
for (Map.Entry<Integer, Integer> uniqueIDs : hash.entrySet()) {
if (uniqueIDs.getValue() == 1) {
flag = true;//Now we have at least one unique element
}
}
if (flag) {
for (Map.Entry<Integer, Integer> uniqueIDs : hash.entrySet()) {
if (uniqueIDs.getValue() == 1) {
System.out.print(uniqueIDs.getKey() "\n");
}
}
} else {
System.out.println("null");
}
}
//Output:
null
Also: a more general advice, in complex codes add the {} because sometimes it gets really hard to understand where a code block starts or ends for someone else trying to read your code, or even yourself sometimes!
