题目:编写程序,在其中同时给出两个不同大小的数字型数组:{4,8,15,32,64,127,256,512}和{2,1,2,4,4,4,8}。利用循环,将第一个数组的数字除以第二个数组相应位置的元素。当结果不是偶数或结果是除数本身,此程序要抛出异常,并捕获和处理相关异常。
提示:
1.自定义两个异常类
2.ArrayIndexOutOfBoundsException类
3.结果不是偶数的判断:if((result%2)!=0)。
4.结果是本身的判断:被除数等于1时。我的解法:
class NotEvenNumber extends Exception{
NotEvenNumber(){
super("结果不是偶数");
}
}
class Itself extends Exception{
Itself(){
super("结果是本身");
}
}
public class CustomException{
public static void main(String[] args){
try{
int[] num1={4,8,15,32,64,127,256,512};
int[] num2={2,1,2,4,4,4,8};
for(int i=0;i<8;i++){
int result=num1[i]/num2[i];
if((result%2)!=0){
throw new NotEvenNumber();
}else if(num2[i]==1){
throw new Itself();
}
System.out.println(result);
}
}catch(NotEvenNumber e1){
e1.printStackTrace();
}catch(Itself e2){
e2.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e3){
System.out.println("数组的大小不等");
}
}
}
提示:
1.自定义两个异常类
2.ArrayIndexOutOfBoundsException类
3.结果不是偶数的判断:if((result%2)!=0)。
4.结果是本身的判断:被除数等于1时。我的解法:
class NotEvenNumber extends Exception{
NotEvenNumber(){
super("结果不是偶数");
}
}
class Itself extends Exception{
Itself(){
super("结果是本身");
}
}
public class CustomException{
public static void main(String[] args){
try{
int[] num1={4,8,15,32,64,127,256,512};
int[] num2={2,1,2,4,4,4,8};
for(int i=0;i<8;i++){
int result=num1[i]/num2[i];
if((result%2)!=0){
throw new NotEvenNumber();
}else if(num2[i]==1){
throw new Itself();
}
System.out.println(result);
}
}catch(NotEvenNumber e1){
e1.printStackTrace();
}catch(Itself e2){
e2.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e3){
System.out.println("数组的大小不等");
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货