-2

the method is to delete any numbers that appear twice in the array. im getting an error in the return statement. help

int x = 0;
  for(int i = 0; i < array.length; i++);
  {
     if(i == 0 || array[i] != array[i-1])
     {
        array[x++] = array[i];                      
     }    
  }
  return x;
user3035626
  • 11
  • 1
  • 4
  • 1
    Should you be removing only duplicates which are neighbours, or any duplicates? – NickJ Dec 05 '13 at 14:55
  • 1
    I don't see how it is even possible to get an error in a return statement that just returns an int... Can you please include the whole method declaration, so we can have a look at the expected return type? – LordOfThePigs Dec 05 '13 at 14:57
  • 1
    post the whole method please. Also this code is not removing all duplicates.... – Blub Dec 05 '13 at 14:59
  • use this link how to remove duplicates from array using HashSet http://stackoverflow.com/questions/10056729/java-remove-duplicates-from-an-array –  Dec 05 '13 at 15:02
  • Is the array supposed to be sorted? – chill Dec 05 '13 at 15:04

2 Answers2

2

Form the overall look of the code, it seems the array is sorted, the following assumes it.

  int x = 0;

You don't need to start from 0 and then check you're not at 0, just start from 1.

  for(int i = 1; i < array.length; i++);
  {

You need to compare to the last copied element, not to the preceding element

     if(array[x] != array[i])
     {

Pre-increment, not post-increment, x always point to a non-duplicated elemnent, you don;t want to overwrite it.

        array[++x] = array[i];                      
     }    
  }

  return x + 1;
}

Finally return the number of remaining elements x + 1 ot the index of last element x, I prefer the former.

chill
  • 16,470
  • 2
  • 40
  • 44
0

On line 2, you have a stray semicolon after the for-loop. It happens to everyone at some point. Your compiler should have complained about the i variable being undeclared though...

Fixed code:

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(removeDuplicates(new int[] {9, 3, 4, 4, 5, 6, 7, 7})));
    }
    public static int[] removeDuplicates(int[] array) {
        int x = 0;
        for(int i = 0; i < array.length; i++)
        {
           if(i == 0 || array[i] != array[i-1])
           {
              array[x++] = array[i];                      
           }    
        }
        return Arrays.copyOf(array, x);
    }
}
quantumkayos
  • 115
  • 6