本帖最后由 Friendy89 于 2013-4-6 09:36 编辑
class NoValueException extends Exception
{
NoValueException(String msg)
{
super(msg);
}
}
interface Shape
{
void getArea();
}
class Rec implements Shape
{
private int len,wid;
Rec(int len,int wid)throws NoValueException
{
if (len<=0||wid<=0)
throw new NoValueException("出现非法值 长宽值");
this.len=len;
this.wid=wid;
}
public void getArea()
{
System.out.println("RecShape="+len*wid);
}
}
class Cir implements Shape
{
public static final double PI = 3.14;
private int r;
Cir(int r)throws NoValueException
{
if (r<=0)
throw new NoValueException("出现非法值 半径");
this.r=r;
}
public void getArea()
{
System.out.println("CirShape="+PI*r*r);
}
}
class ExceptionTest1
{
public static void main(String[] args)
{
try
{
Rec r=new Rec(-3,4);
r.getArea();
Cir c=new Cir(5);
}
catch (NoValueException e)
{
System.out.println(e.toString());
}
System.out.println("Over");
}
}
程序中Rec的len和wid任意一个为负数后,CirShape的值就不运算了,但是r的值为负数时RecShape却可以运算,为什么,代码应该怎么改可以让Rec的len和wid任意一个为负数后,CirShape的值仍可以运算 |