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

3179 views java

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;
        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.

answered question

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

2 Answers


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

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" };

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

Have an answer?


Please login first before posting an answer.