Here I have sample java code which to count number of duplicate numbers in an array.
example:
I have array A[]={3,4,5,3,4,3} so I need the output
3 occurred 3 times
4 occurred 2 times
5 occurred 1 time
How can I get this with my following program.
public class testNumberCount {
public static void main(String[] args) {
String[] temp;
System.out.println("Enter numbers Separated with comma(,)");
String inputSrc = "";
try {
Scanner sc = new Scanner(System.in);
inputSrc = sc.nextLine();
} catch (Exception ex) {
System.out.println("Exception:" + ex.getMessage());
}
temp = inputSrc.split(",");
System.out.println(Arrays.toString(temp));
int[] numberarray = new int[temp.length];
for (int i = 0; i < temp.length; i++) {
numberarray[i] = Integer.parseInt(temp[i]);
}
for (int j = 0; j < numberarray.length; j++) {
for (int k = 0, count = 0; k < numberarray.length; k++) {
if (numberarray[j] == numberarray[k]) {
count++;
}
System.out.println("number " + numberarray[k] + " Occured:" + count + " times.");
}
}
}
}
here my wrong output is:
number 3 Occured:1 times.
number 4 Occured:1 times.
number 5 Occured:1 times.
number 3 Occured:2 times.
number 4 Occured:2 times.
number 3 Occured:3 times.
number 3 Occured:0 times.
number 4 Occured:1 times.
number 5 Occured:1 times.
number 3 Occured:1 times.
number 4 Occured:2 times.
number 3 Occured:2 times.
number 3 Occured:0 times.
number 4 Occured:0 times.
number 5 Occured:1 times.
number 3 Occured:1 times.
number 4 Occured:1 times.
number 3 Occured:1 times.
number 3 Occured:1 times.
number 4 Occured:1 times.
number 5 Occured:1 times.
number 3 Occured:2 times.
number 4 Occured:2 times.
number 3 Occured:3 times.
number 3 Occured:0 times.
number 4 Occured:1 times.
number 5 Occured:1 times.
number 3 Occured:1 times.
number 4 Occured:2 times.
number 3 Occured:2 times.
number 3 Occured:1 times.
number 4 Occured:1 times.
number 5 Occured:1 times.
number 3 Occured:2 times.
number 4 Occured:2 times.
number 3 Occured:3 times.
For this one I'm getting some wrong output, can anybody run and solve my problem.
Your help will be appreciated.
int[] numberArray = { 3, 4, 5, 3, 4, 3 };. Then you can focus on the important bit which is going wrong. Now, what is your actual output?