基础语法-数组的常见问题及常见操作

         基础语法-数组的常见问题及常见操作

                             作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

一.数组操作常见问题

1>.数组索引越界异常(ArrayIndexOutOfBoundsException)

/**
 *     数组常见异常
 * 
 * 
 *     @author 尹正杰
 *
 */
public class ArrayDemo3 {
    public static void main(String[] args) {
        //创建数组
        int[] arr  = new int[3];
        //将arr2保存的是arr对应的引用地址
        int[] arr2 = arr;
        //给数组中的0索引存储数据
        arr[1] = 100;
        //查询数据中指定编号中存储的数据
        for (int index = 0; index < arr.length; index++) {
            System.out.println("arr的索引" + index + "对应的值为" + arr[index]);
        }
        
        //访问到了数组中不存在的索引时会抛出"java.lang.ArrayIndexOutOfBoundsException"异常
        System.out.println(arr[3]);
    }
}

2>.空指针异常(NullPointerException) 

/**
 *     数组常见异常
 * 
 * 
 *     @author 尹正杰
 *
 */
public class ArrayDemo3 {
    public static void main(String[] args) {
        //创建数组
        int[] arr  = new int[3];
        //将arr2保存的是arr对应的引用地址
        int[] arr2 = arr;
        //给数组中的0索引存储数据
        arr[1] = 100;
        //查询数据中指定编号中存储的数据
        for (int index = 0; index < arr.length; index++) {
            System.out.println("arr的索引" + index + "对应的值为" + arr[index]);
        }
        
        //将变量的引用地址指向为null
        arr = null;
        //引用没有指向实例,却在操作实例中的元素
        System.out.println(arr[3]);
    }
}

 

二.获取数组中的最值

/**
 *     获取数组中的最值
 * 
 *     @author 尹正杰
 *
 */
public class ArrayDemo3 {
    public static void main(String[] args) {
        int[] arr = {1,20,3,80,5,200,175,10};
        
        int max = getMax(arr),min = getMin(arr);
        
        System.out.println("arr数组中最大值是:" + max + "最小值是:" + min);
    }
    
    public static int  getMax(int[] arr) {
        //先初始化为数组中的第一个元素
        int max = arr[0];    
        //遍历数组找到最大值
        for (int index = 1; index < arr.length; index++) {
            if (arr[index] > max) {
                max = arr[index];
            }
        }
        return max;
    }
    
    public static int  getMin(int[] arr) {
        //先初始化为数组中的第一个元素
        int min = arr[0];    
        //遍历数组找到最大值
        for (int index = 1; index < arr.length; index++) {
            if (arr[index] < min) {
                min = arr[index];
            }
        }
        return min;
    }
    
}

 

posted @ 2020-01-20 22:58  JasonYin2020  阅读(328)  评论(0编辑  收藏  举报