educative.io

The code I wrote returns the right answer in IntelliJ but not in Educative

Code below

class ReverseWords{
  	public static void reverseWords (char[] sentence) {
			if (sentence.length < 2) {
				return;
			}

			reverseSentence(sentence, 0, sentence.length - 1);

			int wordSearchIndex = 0;
			while (true) {
				int spaceIndex = indexOf(sentence, ' ', wordSearchIndex);

				if (spaceIndex == -1){
					reverseSentence(sentence,  wordSearchIndex, sentence.length - 1);
					return;
				}

				reverseSentence(sentence, wordSearchIndex, spaceIndex - 1);
				wordSearchIndex = spaceIndex + 1;
			}
		}

		private static int indexOf(char[] sentence, char character, int startIndex) {
			int spaceIndex = -1;
			// this could be replaced by indexOf
			for(int i = startIndex; i < sentence.length ; i++) {
				if (sentence[i] == character){
					spaceIndex = i;
					break;
				}
			}

			return spaceIndex;
		}

		private static void reverseSentence(char[] sentence, int startIndex, int endIndex) {
			while (startIndex < endIndex) {
				char temp = sentence[startIndex];
				sentence[startIndex] = sentence[endIndex];
				sentence[endIndex] = temp;
				startIndex++;
				endIndex--;
			}
		}
}  

In IntelliJ if I run like below:

		char[] a = "We love Java".toCharArray();
		reverseWords(a);
		System.out.println(a);

It returns “Java love We”

But the educative test says it returns “Java love W”. I don’t discard the possibility of having something wrong in my code but this is a weird scenario

Hi @Fabio_Souza

You haven’t added the main part. Now it’ll run perfectly.

  public static void reverseWords (char[] sentence) {
    if (sentence.length < 2) {
      return;
    }

    reverseSentence(sentence, 0, sentence.length - 1);

    int wordSearchIndex = 0;
    while (true) {
      int spaceIndex = indexOf(sentence, ' ', wordSearchIndex);

      if (spaceIndex == -1){
        reverseSentence(sentence,  wordSearchIndex, sentence.length - 1);
        return;
      }

      reverseSentence(sentence, wordSearchIndex, spaceIndex - 1);
      wordSearchIndex = spaceIndex + 1;
    }
  }

  private static int indexOf(char[] sentence, char character, int startIndex) {
    int spaceIndex = -1;
    // this could be replaced by indexOf
    for(int i = startIndex; i < sentence.length ; i++) {
      if (sentence[i] == character){
        spaceIndex = i;
        break;
      }
    }

    return spaceIndex;
  }

  private static void reverseSentence(char[] sentence, int startIndex, int endIndex) {
    while (startIndex < endIndex) {
      char temp = sentence[startIndex];
      sentence[startIndex] = sentence[endIndex];
      sentence[endIndex] = temp;
      startIndex++;
      endIndex--;
    }
  }
  public static void main(String[] args) {  
    char[] a = "We love Java".toCharArray();
		reverseWords(a);
		System.out.println(a);
  }
}