/*需求:定义一个方法copyOfRange(int[]arr,int from,int to) * 功能:将数组arr中的索引from(包含from)开始。 * 到索引to结束(不包含to)的元素复制到新数组中,将新数组返回*/ public static void main(String []args){ int []arr={1,2,3,4,5,6,7,8,9}; Scanner scanner=new Scanner(System.in); System.out.println("请输入您想要复制的开头位置0-8:"); int from=scanner.nextInt(); System.out.println("请输入您想要复制的结尾位置0-8:"); int to=scanner.nextInt(); int []newArr=copyOfRange(arr,from,to); for(int i=0;i< newArr.length;i++){ System.out.println(newArr[i]); } } public static int[] copyOfRange(int[]arr,int from,int to){//3-7 (3,4,5,6) int []newArray=new int[to-from]; int index=0; for(int i=from;i<to;i++){ newArray[index] = arr[i]; index++; } return newArray; }
根据所选位置复制数组内容
最新推荐文章于 2024-01-11 14:17:20 发布