实验内容:
源代码:
package exercise;
public class ArrayIndexOutOfBoundsException {
public static void main(String args[]) {
int a[] = null; //定义数组,初始化为null
a = new int[5]; //设置数组大小
System.out.println("程序开始运行"); //程序开始运行
try {
for (int i = 1; i < 10; i++) { //使数组越界
a[i - 1] = i - 2;
}
} catch (Exception e) { //异常类型匹配
System.out.println(e);
System.out.println("数组越界"); //输出类型
} finally {
System.out.println("程序正常结束"); //程序正常结束
}
}
}
运行截图:
实验思路:因为以前遇到过数组越界的问题,实验要实现这个问题还是比较简单的,主要自己给出异常的处理方法就好了。
源代码:
~~~
package exercise;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class DangerEexception extends Exception {
String massage = null;
public DangerException() {
massage = "bibibi 危险物品:";
}
public String toshow() {
return massage;
}
}
class Goods {
String name;
boolean isDanger = true;
public Goods(String name) {
this.name = name;
}
}
public class Machine {
static ArrayList list;
public Machine(ArrayList list) {
this.list = list;
}
public void ListAdd(String name) {
list.add(name);
}
public void ListRemove(String name) {
if (list != null) {
list.remove(name);
}
}
void cheakBag(Goods goods) throws Myexception {
if (goods.isDanger) {
throw new Myexception();
}
}
public static void main(String args[]) {
String n = null;
int flag = 0;
list = new ArrayList();
Machine machine = new Machine(list);
Goods goods = new Goods(n);
machine.ListAdd("打火机"); //添加初始危险物品
machine.ListAdd("管制刀具");
machine.ListAdd("汽油");
machine.ListAdd("化妆品");
Scanner sc = new Scanner(System.in);
System.out.println("1.添加危險物品");
System.out.println("2.刪除危險物品");
System.out.println("3.物品檢查");
System.out.print("请输入操作类型:");
flag = sc.nextInt();
if (flag == 1) {
System.out.print("请输入添加的物品:" + " ");
String x = sc.next();
machine.ListAdd(x);
System.out.println("开始检查:");
System.out.print("待检查物品:" + " ");
n = sc.next();
if (list.contains(n)) {
try {
machine.cheakBag(goods);
} catch (Myexception e) {
System.out.println(e.toshow() + n);
}
} else {
System.out.println("安全通过");
}
}
if (flag == 2) {
System.out.print("请输入删除的物品:" + " ");
String x = sc.next();
machine.ListRemove(x);
System.out.println("开始检查:");
System.out.print("待检查物品:" + " ");
n = sc.next();
if (list.contains(n)) {
try {
machine.cheakBag(goods);
} catch (Myexception e) {
System.out.println(e.toshow() + n);
}
} else {
System.out.println("安全通过");
}
}
if (flag == 3) {
System.out.println("开始检查:");
System.out.print("待检查物品:" + " ");
n = sc.next();
if (list.contains(n)) {
try {
machine.cheakBag(goods);
} catch (Myexception e) {
System.out.println(e.toshow() + n);
}
} else {
System.out.println("安全通过");
}
}
}
}
~~~
运行截图:
添加:
删除:
检查:
感想:这个题目老师上课说过,但是在我拿到题目的时候,就有点看不懂了,我到现在为止还是不知道goods有什么用,如果是只是用来确定isDanger为true的话,那么完全可以定义为String name而不是Goods goods,然后定义的Goods类,也只是存了一个name和一个isDanger,== 有点不明白,应该是知识水平过低,不过还是基本上实现了这个题目的要求。还有在使用ArrayList类时,刚开始我是直接实例化的一个list队列,然后list.add()添加,list.remove()删除,然后想了想,要求好像要可以添加,然后就修改了,直接定义了一个ArrayList lsit属性,就可以实现用户添加和删除了,在代码的最后面,那个flag判断,emm,代码有点多余,不过还是自己慢慢优化吧,因为我觉得问题有点麻烦,然后需要在思考一下再进行修改,还是因为技术不行,得加强训练。
学习总结: