复制一个数组arr1中的值 ,从第2个下标开始到第6个下标结束到数组arr2

package com.fqs.demo;

import java.util.Arrays;

public class ChongZ {
    //复制数组,定义一个方法copyofRange(int[]arr,int from,int to)
    //将数组arr中从索引from(包含from)开始,
    //到索引to(不包含索引to)的元素复制到新数组中,将新数组返回
    
    public static void main(String[] args) {
        int [] arr1= {8,1,2,3,9,7};
        copyofRange(arr1,2,6);
        
 }
    public static void copyofRange(int[]arr1,int from,int to) {
        int [] arr2=new int[to-from];
        //引入计数器 确定新数组开始的下标是count
        int count=0;
        for(int index=from;index<to;index++) {//from从0开始到4结束 0123
            
            arr2[count]=arr1[index];
            count++;//计数器循环加1
            
        }
        System.out.println(Arrays.toString(arr2));
        
        
    }
}

        
    

 

自己写的,缺少对新数组的下标的定义,而且新数组开始下标不应该是0

package com.fqs.demo;

import java.util.Arrays;

public class ChongZ {
    //复制数组,定义一个方法copyofRange(int[]arr,int from,int to)
    //将数组arr中从索引from(包含from)开始,
    //到索引to(不包含索引to)的元素复制到新数组中,将新数组返回
    
    public static void main(String[] args) {
        int [] arr1= {8,1,2,3,9,7};
        copyofRange(arr1,0,3);
        
 }
    public static void copyofRange(int[]arr1,int from,int to) {
        int [] arr2=new int[to];
        for(int index=from;index<to;index++) {//from从0开始到4结束 0123
            
            arr2[index]=arr1[index];
            System.out.println("index:"+index);
            System.out.println("arr2[index]:"+arr2[index]);
        }
        System.out.println(Arrays.toString(arr2));
        
        
    }
}

        
    

 

posted @ 2023-01-15 17:03  胖豆芽  阅读(52)  评论(0编辑  收藏  举报