logo Practice-It logo

BJP3 Self-Check 7.21: swapPairs

Language/Type: Java arrays
Author: Jeff Prouty (on 2013/04/01)

Write a method named swapPairs that accepts an array of strings as a parameter and switches the order of values in a pairwise fashion. Your method should switch the order of the first two values, then switch the order of the next two, switch the order of the next two, and so on. For example, if the array initially stores these values:

String[] a = {"four", "score", "and", "seven", "years", "ago"};

Your method should switch the first pair ("four", "score"), the second pair ("and", "seven") and the third pair ("years", "ago"), to yield this array:

{"score", "four", "seven", "and", "ago", "years"}

If there are an odd number of values, the final element is not moved. For example, if the original list had been:

{"to", "be", "or", "not", "to", "be", "hamlet"}

It would again switch pairs of values, but the final value ("hamlet") would not be moved, yielding this list:

{"be", "to", "not", "or", "be", "to", "hamlet"}

You may assume that the array is not null and that no element of the array is null.

Type your solution here:

This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.