Results 1 to 2 of 2
  1. #1
    daigre7 is offline Member
    Join Date
    Apr 2008
    Posts
    2
    Rep Power
    0

    Default HELP: Trouble with partial filled arrays

    For HW, I have to write a deleteRepeats static method for an array of characters that deletes any character previously listed and returns the new array size. The example the problem gives is:

    char a[10];
    a[0]='a';
    a[1]='b';
    a[2]='a';
    a[3]='c';
    int size = 4;
    size = deleteRepeats(a, size);

    The problem then says after the code is executed, a[0] should be 'a', a[1] should be 'b', a[2] should be 'c' and size is 3. I read the section in my book on partially filled arrays, but I still can't get this method to work properly. Here is my code:

    public static int deleteRepeats(char[] a, int size) {

    size=a.length;
    int numberOfRepeats=0;

    for(int i=0; i<size; i++) {
    for(int j=1; i+j<size; j++) {
    if(a[i]==a[i+j]) {
    a[i+j]=a[(i+j)+1];
    size--;
    numberOfRepeats++;

    }
    }
    }
    return size;
    }

    With that code, when I put in the test array [aabcd], it returns 3, when it should be 4 and it changes the array to [abccd]. I'm sure there's numerous problems with my code. Any help is greatly appreciated.

  2. #2
    daigre7 is offline Member
    Join Date
    Apr 2008
    Posts
    2
    Rep Power
    0

    Default

    BTW, we're learning about ArrayLists now, but we can't use them for this HW. He wants us to learn how to do something like this without it.

    I know that to remove an element in an array you have to do something like shift everything with a higher index to the left and then transfer what you want to a new array of size one less than the original, but I have trouble figuring out the code that does that. Just read the part before my code and let me know how you would go about writing such a method.

Similar Threads

  1. compiling trouble
    By capacitator in forum CLDC and MIDP
    Replies: 4
    Last Post: 06-10-2008, 10:12 PM
  2. Compile Trouble
    By adelgado0723 in forum New To Java
    Replies: 5
    Last Post: 04-21-2008, 02:02 AM
  3. trouble with program
    By jimJohnson in forum New To Java
    Replies: 1
    Last Post: 04-03-2008, 09:29 AM
  4. Having trouble with array
    By ice22 in forum New To Java
    Replies: 3
    Last Post: 11-13-2007, 03:06 AM
  5. JTree trouble
    By Alantie Vala in forum AWT / Swing
    Replies: 3
    Last Post: 07-31-2007, 11:12 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •