11.关于java的练习

练习

一、数组遍历

需求:设计一个方法用于数组遍历,要求遍历的结果是在一行上的。例如:{11,22,33,44,55}

示范:

public class shuzubianli {
    public static void main(String[] args) {
        //1.定义数组
        int[] arr = {11,22,33,44,55};

        //2.调用方法
        bianli(arr);
    }
    //定义方法用于数组的遍历
    public static void bianli(int[] arr){
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if(i == arr.length - 1){
                System.out.print(arr[i]);
            }else{
            System.out.print(arr[i]+ ", ");
            }
        }
        System.out.print("]");
    }
}

在这里插入图片描述

二、数组最大值

需求:设计一个方法求数组的最大值,并将最大值返回

示范:

public class shuzuzuidazhi {
    public static void main(String[] args) {
        //1.定义数组
        int[] arrC = {33,55,22,11,44};

        //2.调用方法求最大值
        int Carrmax = max(arrC);
        
        //3.打印
        System.out.println(Carrmax);
    }
    public static int max(int[] arrC){
        int maxarr = arrC[0];
        for(int i = 1;i < arrC.length;i++){
            if( maxarr < arrC[i]){
                maxarr = arrC[i];
            }
        }
        return maxarr;
    }
}

在这里插入图片描述

三、判断是否存在

需求:定义一个方法判断数据中的某一个数是否存在,将结果返回给调用处。

示范:

public class pandaun {
    public static void main(String[] args) {

        //1.定义一个数组
        int[] arr = {11,33,55,22,25};

        int num = 25;
        //2.调用方法
        boolean cunzai =panIO(arr,num);
        if(cunzai == true){
            System.out.println("此数组内存在");
        }else{
            System.out.println("不存在");
        }
    }
    public static boolean panIO(int[] arrP,int shu){
        for (int i = 0; i < arrP.length; i++) {
            if(arrP[i] == shu){
                return true;
            }
        }
        return false;
    }
}

在这里插入图片描述

四、拷贝数组

需求:定义一个方法copyOFRange(int[] arr,int from,int to)

功能:将数组arr中从索引from(包含from)开始。到索引to结束(不包含to)的元素赋值到新数组中,将新数组返回。

示范:

public class copy {
    public static void main(String[] args) {

        //1.定义原始数组
        int[] yuanArr = {1,2,3,4,5,6,7,8,9};

        //2.调用方法copy数据
        int[] copyArr = copyOfRange(yuanArr, 3, 7);

        //3.遍历copyArr
        for (int i = 0; i < copyArr.length; i++) {
            System.out.println(copyArr[i]);
        }

    }
    public static int[] copyOfRange(int[] arr,int from,int to){
        //1.定义数组(动态数组)
        int[] newArr = new int[to - from];

        //2.把原始数组arr中的from到to上对应的元素,直接 copy 到 newArr 中

        //伪造索引
        int weizao = 0;
        for (int i = from; i < to; i++) {
            newArr[weizao] = arr[i];
            weizao++;
        }

        //3.把新数组返回
        return newArr;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值