i would like to display 2 or more duplicated customers using joptionpane. It is working if there is only 1 duplicate customer but unfortunately the message dialogue wasnt showing if there is 2 or more duplicated customer. Here is my code.
public static void main(String[] args) {
int number;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of customers: "));
int[] one = new int[number];
int[] two = new int[number];
for (int i = 0; i < number; i ) {
one[i] = Integer.parseInt(JOptionPane.showInputDialog("Customer number: "));
}
int y = 0;
for (int i = 0; i < one.length - 1; i ) {
for (int w = i 1; w < one.length; w ) {
if (one[i] == one[w]) {
two[y] = one[w];
y = y 1;
break;
}
}
for (int p = 0; p < y - 1; p ) {
if (one[p] == two[p - 1]) {
y = y - 1;
break;
}
}
}
if (y == 0) {
JOptionPane.showMessageDialog(null, "\nHONEST CUSTOMERS");
} else if (y != 0) {
JOptionPane.showMessageDialog(null, "Duplicates:");
for (int o = 0; o < y; o ) {
JOptionPane.showMessageDialog(null, "Customer #" two[o]);
//jop.showMessageDialog(null, "Duplicates: Customer #" two[l]);
//}
}
}
}
}
How can i show the message dialogue if i want to show 2 or more duplicated customers? thank you for the help.
CodePudding user response:
Break down your code into the following:
- A function that takes the two lists and return a list of pairs of duplicates.
- A function that takes the list of duplicates and create a string stating: "Duplicates: value1, value2..."
- Show message box.
CodePudding user response:
here is an solution for your problem using Collections:
public static Integer[] getDuplicates(Integer[] list) {
List<Integer> duplicates = new ArrayList<>(Arrays.asList(list));
Set<Integer> seen = new HashSet<>(Arrays.asList(list));
for (Integer i : seen) {
duplicates.remove(i);
}
Set<Integer> uniqueDuplicate = new HashSet<>(duplicates);
return uniqueDuplicate.toArray(Integer[]::new);
}
public static void main(String[] args) {
int number;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of customers: "));
Integer[] one = new Integer[number];
for (int i = 0; i < number; i ) {
one[i] = Integer.parseInt(JOptionPane.showInputDialog("Customer number: "));
}
Integer[] two = getDuplicates(one);
if (two.length == 0) {
JOptionPane.showMessageDialog(null, "\nHONEST CUSTOMERS");
} else {
JOptionPane.showMessageDialog(null, "Duplicates:");
for (int o = 0; o < two.length; o ) {
JOptionPane.showMessageDialog(null, "Customer #" two[o]);
// jop.showMessageDialog(null, "Duplicates: Customer #" two[l]);
// }
}
}
}