Java数组参数应用&合并数组"以合并数组实验为例"

mac2024-04-01  34

import java.util.*; import java.util.Scanner; public class Q13 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner console = new Scanner (System.in); /*System.out.println("Type the length for array a1: "); int length = console.nextInt(); System.out.println("Type the length for array a2: "); int length1 = console.nextInt();*/ //定义两个个长度为length length1的数组 int []a1 = {10,20,30,40,50,60}; int []a2 = {10,20,30,40,50,60}; int []a3 = new int[a1.length+a2.length]; /* int []a1 = new int [length]; int []a2 = new int [length1]; for (int i=0;i<a1.length;i++) { System.out.println("Type the #"+(i+1)+" for a1"); a1[i]=console.nextInt(); } for (int a=0;a<a2.length;a++) { System.out.println("Type the #"+(a+1)+" for a2"); a2[a]=console.nextInt(); }*/ //定义数组 a3 = append(a1,a2); System.out.println(Arrays.toString(a3)); } public static int[] append (int[]num,int[]num1){ int []result = new int [num.length+num1.length]; for (int i=0;i<num.length;i++) { result[i]= num[i]; } //前部分复制值 for (int a=num.length;a<result.length;a++) { result [a]= num1[a-num.length]; //后部分从上一部分结束的位置开始复制值 } //合并数组 return result; } }
最新回复(0)