JAVA 两组String类型的数组怎么交换元素
现有等长数组a、b,String[]a=newString[]{"A","B","C","D"},String[]b=newString[]{"O","P","Q","R...
现有等长数组a、b,String[] a = new String[]{"A","B","C","D"},String[] b = new String[]{"O","P","Q","R"},
写一个方法,实现两个数组元素互换,并倒序存储,最终结果是数组a为{"R","Q","P","O"},数组b为{"D","C","B","A"} 展开
写一个方法,实现两个数组元素互换,并倒序存储,最终结果是数组a为{"R","Q","P","O"},数组b为{"D","C","B","A"} 展开
2个回答
展开全部
比较简单啊,新建两个数组c和d,反向循环遍历a和b数组,把每个数组元素放到c和d中就行,放完了,如果你非要用a和b做变量,就在把c和d赋值给a和b。
String [] c=new String [];
String [] d=new Srring [];
for(int i=a.length-1;i>=0;i--){
c[a.length-i-1]=a[i];
}
for(int j=a.length-1;j>=0;j--){
d[b.length-j-1]=b[j];
}
a=c;
b=d;
写完了才发现,你定义的数组有问题,你写的是对象的写法,不是数组的,数组应该是
["A","B","C","D"]
String [] c=new String [];
String [] d=new Srring [];
for(int i=a.length-1;i>=0;i--){
c[a.length-i-1]=a[i];
}
for(int j=a.length-1;j>=0;j--){
d[b.length-j-1]=b[j];
}
a=c;
b=d;
写完了才发现,你定义的数组有问题,你写的是对象的写法,不是数组的,数组应该是
["A","B","C","D"]
展开全部
public class Test{
public static void main(String[] args) {
String[] a = new String[]{"A","B","C","D"};
String[] b = new String[]{"O","P","Q","R"};
for (int i = 0; i < a.length / 2; i++) {
int index = a.length - i - 1;
String tempA = a[i];
String tempB = b[i];
a[i] = b[index];
b[i] = a[index];
a[index] = tempB;
b[index] = tempA;
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询