如何在此代码中运行第三个循环

时间:2017-04-29 06:26:25

标签: java arrays int concatenation

    Scanner s1 = new Scanner(System.in);
    int i,j,k,s,d,p ;
    System.out.println("size");
    s=s1.nextInt() ;
    int arr[] = new int[s] ;
    System.out.println("array 1");
    for (i=0;i<s;i++){
        arr[i]=s1.nextInt() ;
    }
    System.out.println("size ");
    d=s1.nextInt() ;
    int arr1[] = new int[d] ;
    System.out.println("arr2");
    for (j=0;j<d;j++){
        arr1[j]=s1.nextInt() ;
    }
    k=arr.length + arr1.length;
    int arr2[] = new int [k] ;
    for (p=0;p<k;p++){
        arr2[p] = arr[i] + arr[j] ;
    }
    System.out.println("concatenated array");
    for (p=0;p<k;p++){
        System.out.println(arr2[p]);
    }

编译此代码后接收错误ArrayIndexOutOfBounds如何运行第三个循环以使用此代码进行连接。

2 个答案:

答案 0 :(得分:1)

您的阵列大小不相等!!! 例如 在最终的第三阵列20中可能是第一阵列大小5和第二阵列15! 当你添加你的索引时,第一个数组会抛出ArrayIndexOutOfBounds异常!

答案 1 :(得分:0)

您必须分配一个新的数组大小并将数据从 arr arr1 复制到新数组

使用以下代码连接

       Scanner s1 = new Scanner(System.in);

        int i, j, k, s, d, p;
        System.out.println("size");
        s = s1.nextInt();

        int arr[] = new int[s];
        System.out.println("array 1");
        for (i = 0; i < s; i++) {
            arr[i] = s1.nextInt();
        }

        System.out.println("size ");
        d = s1.nextInt();
        int arr1[] = new int[d];
        System.out.println("arr2");
        for (j = 0; j < d; j++) {
            arr1[j] = s1.nextInt();
        }

        if (arr.length > arr1.length) {
            k = arr.length;
        } else {
            k = arr1.length;
        }

        int arr2[] = new int[k];

        int newarr[] = new int[k];
        System.arraycopy(arr, 0, newarr, 0, arr.length);
        arr = newarr;

        int newarr1[] = new int[k];
        System.arraycopy(arr1, 0, newarr1, 0, arr1.length);
        arr1 = newarr1;

        for (p = 0; p < k; p++) {
            arr2[p] = arr[p] + arr1[p];
        }
        System.out.println("concatenated array");
        for (p = 0; p < k; p++) {
            System.out.println(arr2[p]);
        }