日期:2014-05-20  浏览次数:20736 次

java 题目 完成两个数组内容的交换 并输出
我写的代码是这样的
public class jiohuanshuju {
  public static void main(String []args){
  int[] oldArray={1,2,3,4,5,6,7,8,9,0,14,0,15,17,16,0};
  int[] newArray={};
  for(int i=0;i<oldArray.length;i++){
  int j=0;
  if(oldArray[i]!=0){
  newArray[j]=oldArray[i];
  j++;
  }
  }
  int a=newArray.length;
  System.out.print("newArray={"+"\t");
  for(int c=0;c<=a;c++){
  System.out.print(newArray[c]+","+"\t");
  }
  System.out.print("}");
  }
}结果 提示 如下错误
数组下标越界

------解决方案--------------------
提醒你注意结贴给分
Java code


public class Jiohuanshuju {
    public static void main(String []args){
        int[] oldArray={1,2,3,4,5,6,7,8,9,0,14,0,15,17,16,0};
        int[] newArray={11,12,13};

        int[] tempAry=new int[newArray.length];
        for(int i=0;i<newArray.length;i++){
             tempAry[i]=newArray[i];
        }
        newArray=new int[oldArray.length];
        for(int i=0;i<oldArray.length;i++){
////            int j=0;
//            if(oldArray[i]!=0){
//                newArray[j]=oldArray[i];
//                j++;
//            }
            newArray[i]=oldArray[i];
        }
//        int     a=tempAry.length;
//        System.out.print("newArray={"+"\t");
        oldArray=new int[tempAry.length];
        for(int i=0;i<tempAry.length;i++){
            oldArray[i]=tempAry[i];
//            System.out.print(newArray[i]+","+"\t");
        }
//        System.out.print("}");
        System.out.print("old array:");
        for(int i:oldArray){
            System.out.print(i+",");
        }
        System.out.println();
        System.out.print("new array:");
        for(int i:newArray){
            System.out.print(i+","); 
        }
    }
}