-2

I am trying to create an anagram generating program in Java. I am using String.toCharArray(); to store the word character by character. To get the anagrams done, I need to invert the values between two array positions. How do I do this?

Nikaido
  • 4,443
  • 5
  • 30
  • 47

1 Answers1

0

Create a temp variable and store the first value of the array in it. Then set the value of the first element to the value of the last element and then set the last element to the temp variable, then repeat for each index of the array until the middle

char[] chars = char[]{a,b,c}
char temp;
for (int i=0; i < (int)char.length; i++) {
  char temp = chars[i];
  chars[i] = chars[chars.length - i];
  chars[chars.length - i] = temp;
}
Euclidian
  • 17
  • 4
  • 2
    First, you put a typo in `(int)char.length` and then why the need to cast ? array length is an already an `int`. PS : The resulting array will be the same at the end with that loop... – AxelH Mar 21 '18 at 14:18
  • First that's not what he ask for : he wants to swap only two char. Second you mispelled `chars` by `char` in your if statement so it won't work. Third as mentionned by @AxelH `chars.length` is already a int and does not need cast. Finally you said "repeat until the middle" and you made a loop over the whole array so the result will be the same as the input. – vincrichaud Mar 21 '18 at 14:26