Click here to Skip to main content
15,998,231 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to complete this java method. For some reason the entire array gets deleted.

What I have tried:

Java
/**
* Reduces all sequences of 2 or more spaces to 1 space within the
* characters array. If any spaces are removed then the same number
* of Null character '\u0000' will fill the elements at the end of the
* array.
*
* @param characters The series of characters that may have more than one
*     space in a row when calling. On return the array of characters will
*     not have more than one space in a row and there may be '\u0000'
*     characters at the end of the array.
*/
public static void removeDuplicateSpaces(char[] characters) {

	for (int i = 0; i < characters.length - 1; i++) {
		if (characters[i] == ' ' && characters[i + 1] == ' ') {
			int k = i + 1;
			int n = 0;
			char j='\u0000';
			while (n<characters.length-1){>
				for (k=i+1; k < characters.length-1; k++){
					if (characters[k]==' '){
						characters[k]=j;
					}
					for ( int l = 0; l < characters.length-1;l++){
						characters[l]=characters[l+1];
					}
				}
				n++;
			}
		}
	}
Posted
Updated 7-Mar-16 22:51pm
v3

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

Think how you would do by hand, compare with what you do in your code, be careful to details.
 
Share this answer
 
v3
Java
char j='\u0000';
while (n<characters.length-1){>
	for (k=i+1; k < characters.length-1; k++){
		if (characters[k]==' '){
			characters[k]=j;
		}

You are replacing a space with a null which indicates the end of the string. All characters beyond the null will now be ignored. You are supposed to remove duplicate spaces, and add null characters at the end of the array where the previous characters have been moved from.

You should move the remaining characters in the array up the array, overwriting the repeated spaces. You then add nulls at the end of the aray according to the number of spaces overwritten. Try writing it down on paper first to see exactly what each step should do, before converting to code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900