0

I'm trying to write a code that returns a new array which swaps every pair of elements. If there is an odd number of elements, the last element remains the same.

Currently what I have is this which doesn't seem to be working at all. I keep returning a nullpointerexception error when trying to test it

public static String[] pairSwap(String[] inputArray) {
    String[] outputArray = new String[inputArray.length];
    for (int i = 0; i < inputArray.length; i += 2) {

        inputArray[i] = outputArray[i + 1];
        inputArray[i + 1] = outputArray[i];

        if (inputArray.length % 2 != 0) {
            inputArray[inputArray.length] = outputArray[inputArray.length];
        }
    }
    return outputArray;
}
azro
  • 53,056
  • 7
  • 34
  • 70
  • The odd-length handling is setting the `inputArray` element, not the `outputArray` element. (It also doesn't need to be inside the loop) – Andy Turner Mar 19 '20 at 11:33
  • You update `inputArray` instead of `outputArray` change all. Also the `if` should be OUTSIDE the loop https://ideone.com/yTgf5l – azro Mar 19 '20 at 11:35
  • The last element of the input array is inputArray[inputArray.length - 1]. Same for the output array. Arrays go from 0 to length - 1. – Gilbert Le Blanc Mar 19 '20 at 13:26

0 Answers0