The requirements are to check for duplicate items in the array and delete it, the remaining items in the array must then shift to the left.
I wrote this:
public class TestRepeat {
public static int deleteRepeats(char[] ch) {
int count = 0;
for (int x = 0; x < ch.length; x++) {
for (int y = x + 1; y < ch.length; y++) {
if (ch[x] == ch[y]) {
for (int k = y; k < ch.length - 1; k++) {//shifts the array to the right if its a duplicate
ch[k] = ch[k + 1];
}
ch[ch.length - 1] = ' ';//replaces the last array with a blank
}
}
}
for (int q = 0; q < ch.length; q++) {
if (ch[q] == ' ') {
count++;
}
}
return count;//returns the number of deleted items
}
public static void main(String[] args) {
char[] ch = {'k', 'a', 'm', 'o', 'k', 'm', 'y', 'm', 'k', 'k', 'x', 'm', 'm', 'o'};
System.out.print("The original array is: ");
System.out.println(ch);
System.out.println("Number of deleted characters: " + deleteRepeats(ch));
System.out.print("The new array is: ");
System.out.println(ch);
}
}
its supposed to return:
The original array is: kamokmymkkxmmo
Number of deleted characters: 8
The new array is: kamoyx
but instead is returning:
The original array is: kamokmymkkxmmo
Number of deleted characters: 6
The new array is: kamoykxm
What is causing the problem and how can I fix it?