创建两个大小为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));
}
}
只需对循环使用两个; 不需要嵌套循环。 请参阅下面的代码。
for(int i = 0; i < 5; i++){
arr[i] = ar1[i];
}
for(int i = 0; i < 5; i++){
arr[i + 5] = ar2[i];
}
您还可以将其组合到一个for
循环中。
for(int i = 0; i < 5; i++){
arr[i] = ar1[i];
arr[i + 5] = ar2[i];
}
对于较大的数组,使用System.ArrayCopy
将更有效,因为它使用本机调用。 请参阅下面的代码。
System.arraycopy(ar1, 0, arr, 0, ar1.length);
System.arraycopy(ar2, 0, arr, ar1.length, ar2.length);
import java.util.Scanner;
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++)
{
arr[i] = ar1[i];
arr[i+5] = ar2[i];
}
System.out.println("Elements of the array 3:");
for(int i=0; i< 5; i++)
{
System.out.print(arr[i]+" ");
}
}
}
import java.util.Scanner;
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();
arr[i] = ar1[i];
}
System.out.println("Enter the elements of the array 2:");
for(int i = 0; i < ar2.length; i++)
{
ar2[i] = sc.nextInt();
arr[i+5] = ar2[i];
}
System.out.println("Elements of the array 3:");
for(int i=0; i< 5; i++)
{
System.out.print(arr[i]+" ");
}
}
}