方法的重载,方法的调用和数组,及数组的排序

1.方法的重载 (在同一个类中,方法名相同但参数列表不同的方法叫做方法的重载)

2.类中方法的调用:

public class Demo1 {

    public static void main(String[] args) {

        int a = 5;
        int b = 2;
        int c = 6;
        getMax(a,b,c);

         getMax();
    }

    //求两个数的最大值
    public static int getMax(int a, int b) {
     return a > b ? a : b ;
    }
    //求三个数的最大值
    public static int getMax(int a, int b,int c) {
        //使用已经写好的2个数求最大值的方法
        int max = getMax(a, b);
        return getMax(max, c);
    }
    //求四个数的最大值
    public static int getMax(int a, int b,int c,int d) {
        //使用已经写好的3个数求最大值的方法
        int max = getMax(a, b, c);
        return getMax(max, d);
    }
    //求五个数的最大值
        public static int getMax(int a, int b,int c,int d,int e) {
            //使用已经写好的4个数求最大值的方法
            int max = getMax(a, b, c, d);
            return getMax(max, e);
        }
  }

2.数组:可以存放一组相同类型数据的容器,根据下标存放数据,下标从0开始。数组是引用数据类型

  2.1 数组的定义:数据类型[ ] 数组名 = 初始化值

        //数组的形式1:
        double[] arr1 = new double[3];//数组长度一旦限定不可更改
        //数组的形式2:
        int[] arr2 = new int[] {1, 2, 3};//定义数组的同时初始化数组元素的值
        //简便定义数组形式
        int[] arr3 = {1,2,3};

3.堆内存特点:1.有默认的初始值
        2.有地址
        3.有垃圾回收机制
 栈内存特定:程序执行完会执行弹栈

4.数组的处理方法

 4.1遍历并打印数组

   public static void printArr(int[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                System.out.print(arr[arr.length - 1] + "]");
            }else {
            System.out.print(arr[i] + ", ");
        }
      }
        System.out.println();
    }

  4.2 数组的选择排序

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i; j < arr.length - 1; j++) {
                if (arr[i] > arr[j + 1]) {
                    int temp = arr[i];
                    arr[i] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

  4.3 数组的冒泡排序

    public static void popSort(int[] arr) {
        for (int i = 0 ;i < arr.length - 1;i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

5. 数组处理中常见的异常

  数组越界异常  ArrayIndexOutOfBoundsException
  空指针异常   NullPointerException



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值