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

我有以下数组。


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

}


慕斯王
浏览 133回答 3
3回答

Cats萌萌

看起来您走在正确的轨道上,但您实际上应该交换数组中的元素。另外,不要返回String. 并遵循 Java 命名约定。喜欢,public static void swapString(String[] arr) {&nbsp; &nbsp; for (int i = 0; i + 1 < arr.length; i += 2) {&nbsp; &nbsp; &nbsp; &nbsp; String t = arr[i + 1];&nbsp; &nbsp; &nbsp; &nbsp; arr[i + 1] = arr[i];&nbsp; &nbsp; &nbsp; &nbsp; arr[i] = t;&nbsp; &nbsp; }}然后像这样调用/测试它,public static void main(String[] args) {&nbsp; &nbsp; String[] arr = { "Cecilia", "Jasmine", "David", "John", "Sylvia", "Bill", "Austin",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Bernardo", "Christopher", "Leticia", "Ronaldo" };&nbsp; &nbsp; System.out.println(Arrays.toString(arr));&nbsp; &nbsp; swapString(arr);&nbsp; &nbsp; 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]

慕田峪7331174

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

慕容708150

您只需要从 0 开始,并打印当前索引(带空格,没有返回行)和以下内容,但在打印时交换它们,然后增加 2 :String current, next;for (int i=0 ; i<arr.length-1 ; i+= 2) {&nbsp; &nbsp; current = arr[i];&nbsp; &nbsp; next = arr[i+1];&nbsp; &nbsp; System.out.print(next + " " + current + " ");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java