3 回答
TA贡献1805条经验 获得超9个赞
看起来您走在正确的轨道上,但您实际上应该交换数组中的元素。另外,不要返回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]
TA贡献1828条经验 获得超13个赞
这可能有帮助
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]);
}
TA贡献1831条经验 获得超4个赞
您只需要从 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 + " ");
}
添加回答
举报