Printing distinct integers in an array

后端 未结 8 2082
遇见更好的自我
遇见更好的自我 2020-12-22 06:17

I\'m trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.

8条回答
  •  臣服心动
    2020-12-22 06:49

    First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").

    Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!

    Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.

    A proper implementation of CheckDuplicate() would be:

    public static void checkDuplicate(int array []) {
      for (int i = 0; i < array.length; i++) {
        boolean found = false;
        for (int j = 0; j < i; j++)
          if (array[i] == array[j]) {
            found = true;
            break;
          }
        if (!found)
          System.out.println(array[i]);
      }
    }
    

    But of course, some kind of Set would be much more efficient for bigger arrays...


    EDIT: Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...

提交回复
热议问题