I am very new to java and a junior java developer. The requirement asks to get the list of customerid and if the list contains customer ids which are repeated, then it would display the dupliate record. And if there are no customer id which are repeated then it would display no duplicate record. I have tried but stuck at the point where the customerid is repeated more than twice. My code works fine till the point the customerid is repeated twice. For ex:
Customerid:(5 input)
123
123
234
123
234
Output(Expected)
123
234
Actual:
123
123
123
234
for Scenario where there is no duplicate element, it would print no records found. Input: 123 234 345 456 567 Output: No records found
Output of my code is wrong when the repetition is more than twice. Kindly Advice. Code:
package firstpack;
import java.util.Scanner;
public class Class9 {
public static void main(String[] args) {
int a, i;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
long[] b = new long[a];
for (i = 0; i <= (b.length - 1); ) {
do {
b[i] = sc.nextLong();
i++;
}
while (i <= a - 1);
}
System.out.println("Duplicate records :");
for (i = 0; i < b.length - 1; i++) {
for (int j = i + 1; j < b.length; j++) {
if ((b[i] == (b[j])) && (i != j)) {
System.out.println(b[j]);
}
}
}
}
ifcondition, and every time you find a duplicate - you're printing it. So if a dup exists more than twice - you'll print it more times... What you probably want to do instead is: every time you run into a dup - add it to aHashSet. The set will avoid duplications - so when you try to insert the same thing twice - it won't work and the set will retain only one copy. After you're done with the for-loops, simply print out the set.