编写使用循环交换数组中每两个连续字符串的方法

时间:2018-11-07 02:46:07

标签: java arrays loops

我有以下数组。

{"Cecilia", "Jasmine", "David", "John", "Sylvia", "Bill", "Austin", "Bernardo", "Christopher", "Leticia", "Ronaldo"}

应该打印如下:

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

3 个答案:

答案 0 :(得分:4)

看来您走在正确的轨道上,但实际上您应该交换数组中的元素。另外,请勿返回String。并遵循Java命名约定。喜欢,

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

然后调用/测试它,

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

我得到了(按要求)

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

答案 1 :(得分:0)

您只需要从0开始,然后打印当前索引(带空格,没有返回行)及以下内容,但是通过在打印时交换它们,然后增加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

答案 2 :(得分:0)

这可能有帮助

int i,l=s.length;   
for(i=1;i<l;i+=2)
{
    System.out.println(s[i]);
    //i--;
    System.out.println(s[i-1]);
}
if(l%2!=0)//if the array is of odd length,it will include the last element 
   System.out.println(s[l-1]);
}