java实现一个IndexOutOfBoundException受检异常类,并定义一个班级类,在班级类中定义一个方法addArray(Student s, int index),用于实现将Student s加入到这个班级,该方法第一个参数是待加入的学生,第二个参数是加入到班级中学生的指定位置。若加入的位置超出了班级中的存储范围,则抛出上面定义的异常类的对象。主类中,创建多个学生类的对象,并不断用addArray进行测试。
import java.util.Scanner;
import java IndexOutOfBoundException;
public class Test extends Exception {
String s=null;
Student s1=new Student("张三","女",21);
Student s2=new Student("李四","女",21);
Student s3=new Student("王五","男",21);
Student s4=new Student("王六","男",21);
Student s5=new Student("张四","女",21);
Scanner sc=new Scanner(System.in);
int index=sc.nextInt()
try {
s1.add2Array();
}catch(IndexOutOfBoundException e)
{e.printStackTrace();
System.out.printf("error");
}
}
没有你的学生类,就写个string的list,string换成你的student就行了,大致可以这样
public class zz {
static List<String> a=new ArrayList();
public static void main(String[] args) {
zz.addArray("1", 0);
zz.addArray("2",1);
zz.addArray("3",3);
}
public static void addArray(String string,int index){
if (index>a.size()){
throw new IndexOutOfBoundsException("error+IndexOutOfBoundException");
}
a.add(index, string);
}
}