java异常处理经典例子

public class ArrayAverage {       //求加权平均数
public static double weightedAverage(int value[],int weight[]) // 定义静态方法求加权平均数,传入数组参数
{
if(value.length==0)  //如果value为null,则抛出空对象异常,若value长度为0 返回0
return 0;    
double sum=0.0;  
int i=0;
if(weight!=null&&weight.length!=0) //如果权值不为空且不为0则 进行加权平均数的运算
  {
int minlen=value.length for(i=0;i sum+=weight[i]*value[i];
}
for(;i sum=sum+value[i];   
return sum/value.length;   //返回加权平均数
}
public static int[] toIntArray(String str[])  //定义函数获得数组中的整数,返回一个int[]类型的数组
{
if(str==null || str.length==0)   //如果数组参数为空或长度为0
return null;
int temp[]=new int[str.length];  //创建一个长度相同的控数组temp
int count=0,i=0;  
while(i {
try   //存在潜在的异常语句,当不能转化为十进制的整数时,抛出异常
{
temp[count]=Integer.parseInt(str[i]);  //将str[]转化为整数存在temp中,parseInt默认转化为十进制
count++;
}
catch(NumberFormatException ex)  //捕获异常对象并进行处理的语句
{
try  //当不能转化为十六进制的整数时,抛出异常
{
temp[count]=Integer.parseInt(str[i],16); //将str[]转化为十六进制的整数
count++;
}
catch(NumberFormatException nfex) //捕获异常对象并作出处理的语句
{
System.out.println(str[i]+"字符串不能转换为整数"+nfex.toString()); //输出该字符串不能转化为整数
}
}  //如果获得一个整数将会存在temp数组中
catch(Exception ex)  // 捕获异常对象,一般从子类到父类,从小到大
{
ex.printStackTrace(); //打印出一个追踪的错误信息
}
finally
{
i++;
}
}
if(count==temp.length) //当数组放满时返回temp
return temp;
int value[]=new int[count];//当数组不满时
System.arraycopy(temp,0,value,0,count); //将temp中的有效数组复制到value中并返回
return value;
}
public static void main(String args[]) 
{
String valuestr[]={"10","20","30","40","50","x","60","70"};
String weightstr[]={"a","b","c","d","e","f","g"};
int value[]=toIntArray(valuestr);  //将valuestr数组整数化到value数组中
System.out.print("value[]数组: ");
System.out.println(value);
int weight[]=toIntArray(weightstr); //将weightstr数组整数化到weight数组中
System.out.print("weight[]数组: ");
System.out.println(weight);
System.out.println("weightedAverage(value,weight)="+weightedAverage(value,weight));
System.out.println("weightedAverage(value,weight)="+weightedAverage(value,null));
}
}

你可能感兴趣的:(异常处理)