Java 用其他数组填充数组

Java 用其他数组填充数组,java,Java,创建两个大小为5的数组A和B以及大小为10的数组C。接受两个数组A和B中的数字。 填充数组C,使前五个位置占据数组中的数字 A和其余五个位置占据数组B中的数字 import java.util.*; public class Record22_ArrayFill { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] a

创建两个大小为5的数组A和B以及大小为10的数组C。接受两个数组A和B中的数字。 填充数组C,使前五个位置占据数组中的数字 A和其余五个位置占据数组B中的数字

import java.util.*; 
  
public class Record22_ArrayFill
{ 
    public static void main(String[] args) 
    { 
        Scanner sc = new Scanner(System.in);
        int[] ar1 = new int[5];
        int[] ar2 = new int[5];
        int[] arr = new int[10];
        System.out.println("Enter the elements of the array 1:");
        for(int i = 0; i < ar1.length; i++)
        {
            ar1[i] = sc.nextInt();
        }
        System.out.println("Enter the elements of the array 2:");
        for(int i = 0; i < ar2.length; i++)
        {
            ar2[i] = sc.nextInt();
        }
        for(int i=0; i< 5; i++)
        {
            for(int j=0; j< 5; j++)
            {
                arr[j] = ar1[i];
            }
        }
        for(int i=0; i< 5; i++)
        {
            for(int j=5; j< 10; j++)
            {
                arr[j] = ar2[i];
            }
        }
        System.out.println(Arrays.toString(arr));
    } 
}
只需使用两个循环;不需要嵌套循环。请参阅下面的代码

对于较大的阵列,使用将更加有效,因为它使用本机调用。请参阅下面的代码


这看起来像一道考试题?p、 你可以通过修正for循环来解决你的问题,在你不需要做双循环的时候,试试类似于forint i=0的方法;i<5;i++执行两次,在第二个循环中,只需在循环内为最终数组的索引中添加5。希望有帮助。
for(int i = 0; i < 5; i++){
    arr[i] = ar1[i];
}
for(int i = 0; i < 5; i++){
    arr[i + 5] = ar2[i];
}
for(int i = 0; i < 5; i++){
    arr[i] = ar1[i];
    arr[i + 5] = ar2[i];
}
System.arraycopy(ar1, 0, arr, 0, ar1.length);
System.arraycopy(ar2, 0, arr, ar1.length, ar2.length);