0

I am trying to print only the non-duplicate (distinct) characters in an array of characters. I am probably doing something elementary wrong. Can you explain and show me my mistake? This is my code:

public class MyDistinctCharacters {

    public static void printDistinctCharacters(char[] arr){

        for(int i=0;i<arr.length;i++){
            boolean isDistinct = false;
            for(int j=0;j<i;j++){
                if(arr[i] == arr[j]){
                    isDistinct = true;
                    break;
                }
            }
            if(!isDistinct){
                System.out.print(arr[i]+" ");
            }
        }
    }

    public static void main(String a[]){

        char[] chars = {a,b,c,c,d,e,e,f};
        MyDistinctCharacters.printDistinctCharacters(chars);
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Vilkas
  • 1
  • 1

2 Answers2

0

There are a couple of things. First I'm not sure if you mean print every character exactly once, or only print characters for which there are no duplicates. It sounds like you mean the second. If so, here's my answer:

First, the isDistinct variable should be called isDuplicate based on your code. Second, in the inner loop you have a condition j < i. As a result, if your array is 10 characters long and i=0, the code will not check the array for duplicates at all and just print out the first character for i=0.

To fix this, you need to check the whole array for duplicates, just ensure that you are not referencing the same character i. So the inner loop should be:

for(int j=0;j<arr.length;j++){
    if(i != j && arr[i] == arr[j]){
        isDuplicate = true;
        break;
    }
}
ValtsBlukis
  • 458
  • 4
  • 11
0

The characters should be quoted in the array definition:

char[] chars = {'a', 'b', 'c', 'c', 'd', 'e', 'e', 'f'};

I'm pretty sure it doesn't compile the way you wrote it.

Concerning the inner loop I agree with @ValtsBlukis. The loop index should run to arr.length - there is no reason to stop at i. Also your logic is flawed in the inner loop body. You're basically saying isDistinct shall be true, if there are multiple elements with the same value (up to i).

nucleon
  • 1,128
  • 1
  • 6
  • 19