public class TestOverload {
public static void main(String [] args){
CalculatePerimeter perimeter;
perimeter=new CalculatePerimeter();
System.out.println("The perimeter of circle is:"+perimeter.getPerimeter(4));
System.out.println("The perimeter of rectangle is:"+perimeter.getPerimeter(3,5));
System.out.println("The perimeter of triangle is:"+perimeter.getPerimeter(-3,2,3));
}
}
class CalculatePerimeter{
public double getPerimeter(double radius){
if(radius<0){
radius=0;
}
return 2*Math.PI*radius;
}
public double getPerimeter(double length,double width){
if(length<0||width<0){
length=0;
width=0;
}
return 2*(length+width);
}
public double getPerimeter(double line_1,double line_2,double line_3){
double temp;
if(line_1>line_2){
temp=line_2;
line_2=line_1;
line_1=temp;
}
if(line_1>line_3){
temp=line_3;
line_3=line_1;
line_1=temp;
}
if(line_2>line_3){
temp=line_3;
line_3=line_2;
line_2=temp;
}
if((line_1+line_2<=line_3)||line_1<0||line_2<0||line_3<0){
line_1=line_2=line_3=0;
}
return line_1+line_2+line_3;
}
}
在熟悉方法重载。
问题:在这三个方法中,判断了输入异常后,如何直接跳出并且不执行return语句。
------解决方案--------------------
直接抛出异常。外部别catch就能直接跳出
------解决方案--------------------
抛出异常,或将返回值定义为Double,在出现输入异常时 return null