《JAVA异常处理》ArrayIndexOutOfBoundsException异常与OutOfMemoryError错误
来源:互联网 发布:linux 覆盖式复制 编辑:程序博客网 时间:2024/06/05 15:24
1、【ArrayIndexOutOfBoundsException异常】编写一个程序,创建一个由100个随机选取的整数构成的数组;提示用户输入数组下标,然后显示元素的值,如果指定的下标越界,显示消息out of bounds。
2、【OutOfMemoryError错误】编写一个程序,它能导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。
//1package shiyan6;import java.util.Scanner;public class demo2 { public static void main(String[] args){ Scanner input = new Scanner(System.in); boolean inputIndex= true; int[]shuzu=new int[100]; //随机生成数字存入数组 for (int i=0;i<100;i++){ shuzu[i] = new java.util.Random().nextInt(100); } do{ try { System.out.println("Please in put the index of the shuzu[0-100]:"); int index = input.nextInt(); System.out.println(shuzu[index]); inputIndex= false;//输出之后退出 } catch (ArrayIndexOutOfBoundsException ex) { System.out.println("out of bounds!"); System.out.println("Please input again,index must be inputed from (0-100)"); } } while (inputIndex); } }
//2 方法一 不断输入数组的长度大小(在int范围之内),直到数组长度太大爆了package shiyan6;import java.util.Scanner;public class demo3 { public static void main(String[] args) { boolean Stop =true; do{ try { System.out.println("Input an integer in of the range of (-2147483647~2147483647)"); Scanner input = new Scanner(System.in); int len = input.nextInt(); int largArray[] = new int[len]; Stop = false; } catch (OutOfMemoryError e) { System.out.println("OutOfMemoryError !"); } }while(Stop); } }
//2 方法二 直接产生一个最大的int 类型的整数直到数组长度爆了package shiyan6;import java.util.Scanner;public class demo3 { public static void main(String[] args) { try { int len = Integer.MAX_VALUE; int largArray[] = new int[len]; System.out.println(len); } catch (OutOfMemoryError e) { e.printStackTrace(); System.out.println("Please input the munber of the array you want(lpease input small):"); Scanner input = new Scanner(System.in); int len2 = input.nextInt(); System.out.println("The maxindex of the array you input is:"+len2); } }}
这些实验可以灵活变通,因为有挺多种方式写的,重要在于捕获与处理的过程,生成随机付给数组的代码也可以是:Array[i] = (int)(System.currentTimeMillis()),即利用产生系统的时间数并转化为整形,只是他们的范围太近了不好区分。初学者的看法,期待指正。
1 0
- 《JAVA异常处理》ArrayIndexOutOfBoundsException异常与OutOfMemoryError错误
- ArrayIndexOutOfBoundsException异常
- java.lang.ArrayIndexOutOfBoundsException异常问题
- 异常与错误处理
- 错误与异常处理
- 异常与错误处理
- 错误与异常处理
- 错误与异常处理
- 错误与异常处理
- Java内存溢出错误:OutOfMemoryError异常分析
- java错误异常处理
- Java异常处理错误
- java.lang.OutOfMemoryError异常处理总结
- java.lang.OutOfMemoryError: PermGen space异常处理
- 异常处理 java.lang.OutOfMemoryError: PermGen space
- java异常与异常处理
- Java异常与异常处理
- Java 异常与异常处理
- 计算机硬件组成
- ArrayBlockingQueue和LinkedBlockingQueue的使用
- 简单研究跨域的几种方法
- kettle运行时报错 could not create java virtual machine
- oracle拼接字段和group by的使用
- 《JAVA异常处理》ArrayIndexOutOfBoundsException异常与OutOfMemoryError错误
- Struts2中集合在jsp中循环显示
- TCP/IP、Http、Socket的区别
- 第4章:分治策略 ——最大字数组问题
- 数据仓库介绍
- LeetCode-35.Search Insert Position
- JAVA SE 8 学习笔记(四)日期和时间API
- Android中的WebView进行直接加载网页
- 映射集-Map