Results 1 to 2 of 2
- 04-06-2008, 07:59 PM #1
Member
- Join Date
- Apr 2008
- Posts
- 2
- Rep Power
- 0
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.
- 04-07-2008, 02:05 AM #2
Member
- Join Date
- Apr 2008
- Posts
- 2
- Rep Power
- 0
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
-
compiling trouble
By capacitator in forum CLDC and MIDPReplies: 4Last Post: 06-10-2008, 10:12 PM -
Compile Trouble
By adelgado0723 in forum New To JavaReplies: 5Last Post: 04-21-2008, 02:02 AM -
trouble with program
By jimJohnson in forum New To JavaReplies: 1Last Post: 04-03-2008, 09:29 AM -
Having trouble with array
By ice22 in forum New To JavaReplies: 3Last Post: 11-13-2007, 03:06 AM -
JTree trouble
By Alantie Vala in forum AWT / SwingReplies: 3Last Post: 07-31-2007, 11:12 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks