(1)定义一个接口Inf,含有常量π和一个实现计算功能的方法calculate(),再分别定义一个面积类area和一个周长类circumference,各自按计算圆面积和圆周长具体实现接口中的方法,并以...
(1) 定义一个接口Inf,含有常量π和一个实现计算功能的方法calculate( ),再分别定义一个面积类area和一个周长类circumference,各自按计算圆面积和圆周长具体实现接口中的方法,并以半径为5来测试这两个类。
interface Inf
{
double PI=3.1415926;
double calculate();
}
class area implements Inf
{
double r;
public area(double r1){r=r1;}
public double calculate()
{
return PI*r*r;
}
public void output()
{
System.out.println("圆面积为:" + this.calculate());
}
}
class circumference implements Inf
{
double r;
public circumference(double r1){r=r1;}
public double calculate()
{
return 2*PI*r;
}
public void output()
{
System.out.println("圆周长为:" + this.calculate());
}
}
public class te1
{
public static void main(String args[])
{
area a = new area(5);
a.output();
circumference c = new circumference(5);
c.output();
}
}
(2) 定义一个类,在main方法的try块中产生并抛出一个异常,在catch块中捕获异常,并输出相应信息,同时加入finally子句,输出信息,证明它的无条件执行。
public class te2{
public static void main(String args[])
{
try {throw new MyException();}
catch(Exception e)
{
System.out.println("It's caught");
}
finally
{
System.out.println("It's finally caught");
}
}
}
class MyException extends Exception{}
(3) 定义一个类Caculate实现10以内的整数加减法的计算。自定义一个异常类NumberRangeException,当试图进行超范围运算时,产生相应的信息。编写应用程序进行测试。
import java.io.*;
class NumberRangeException extends Exception
{
public NumberRangeException()
{
}
}
public class te3
{
public static void main(String args[])
{
int a = 0;
int b = 0;
int add=0;
int sub=0;
while(true)
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try
{
a = Integer.parseInt(input.readLine());
b = Integer.parseInt(input.readLine());
}
catch (NumberFormatException e)
{
}
catch (IOException e)
{
}
try
{
if (a > 10||b > 10)
throw new NumberRangeException();
else
add=a+b;
sub=a-b;
break;
}
catch (NumberRangeException e)
{
System.out.println("您所输入的数字大于10!");
break;
}
}
System.out.println("两数相加得:"+add);
System.out.println("两数相减得:"+sub);
}
}
展开