# Writing a method that swaps every two consecutive strings in an array using loops

3179 views
6

I have an array `{"Cecilia", "Jasmine", "David", "John", "Sylvia", "Bill", "Austin", "Bernardo", "Christopher", "Leticia", "Ronaldo"}` and it is supposed to be printed like: `"Jasmine" "Cecilia" "John" "David"` and so on.

``````    public static String SwapString(String [] arr)
{
String str;
String str1;
if(arr.length%2!=0)
{
for (int i=1;i<arr.length-1;i+= 2)
{
str = arr[i-1];
str1 = arr[i+1];
System.out.println (arr[i]+str1);

}
}
return " ";
}
``````

I have this so far.

That's great. What exactly is your question about what you have so far? What does it do and what did you expect it to do instead?

You are not updating the array, not sure if you are supposed

It looks like you're swapping the one behind `i`, the one in front of `i` and then incrementing `i` by two. Which would make the one that was in front of `i` the one behind, so then itll get swapped with the one in front, and then once `i+=2` is reached itll become the one behind again etc

10

You just need to start at 0, and print current index (with space, and no return line) and the following but by swapping them at print, then go up by 2 :

``````String current, next;
for (int i=0 ; i<arr.length-1 ; i+= 2) {
current = arr[i];
next = arr[i+1];
System.out.print(next + " " + current + " ");
}
``````

`Code Demo`

posted this
10

It appears you were on the right track, but you should actually swap the elements in the array. Also, don't return a `String`. And follow Java naming conventions. Like,

``````public static void swapString(String[] arr) {
for (int i = 0; i + 1 < arr.length; i += 2) {
String t = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = t;
}
}
``````

Then call / test it like,

``````public static void main(String[] args) {
String[] arr = { "Cecilia", "Jasmine", "David", "John", "Sylvia", "Bill", "Austin",
"Bernardo", "Christopher", "Leticia", "Ronaldo" };
System.out.println(Arrays.toString(arr));
swapString(arr);
System.out.println(Arrays.toString(arr));
}
``````

I get (as requested)

``````[Cecilia, Jasmine, David, John, Sylvia, Bill, Austin, Bernardo, Christopher, Leticia, Ronaldo]
[Jasmine, Cecilia, John, David, Bill, Sylvia, Bernardo, Austin, Leticia, Christopher, Ronaldo]
``````

posted this