计算各种图形的周长(接口与多态)
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
定义接口Shape,定义求周长的方法length()。
定义如下类实现接口Shape的抽象方法:
(1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。
定义测试类ShapeTest,用Shape接口定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。
Input
输入多组数值型数据(double);
一行中若有1个数,表示圆的半径;
一行中若有2个数(中间用空格间隔),表示长方形的长度、宽度。
一行中若有3个数(中间用空格间隔),表示三角形的三边的长度。
若输入数据中有负数,则不表示任何图形,周长为0。
Output
行数与输入相对应,数值为根据每行输入数据求得的图形的周长(保留2位小数)。
Example Input
1 2 3 4 5 6 2 -2 -2 -3
Example Output
6.28 10.00 15.00 12.56 0.000.00
import java.text.DecimalFormat; import java.util.Scanner; class rectangle { double x, y, z, x1, y1, z1; public rectangle(double x1, double y1, double z1) { this.x1 = x1; this.y1 = y1; this.z1 = z1; } public rectangle(double x1, double y1) { x = x1; y = y1; } public rectangle(double x1) { z = x1; } double area() { return z * 2 * 3.14; } double area1() { return (x + y) * 2; } double area2() { return x1 + y1 + z1; } }; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { DecimalFormat two = new DecimalFormat("#0.00"); String str = sc.nextLine(); String[] strs = str.split(" "); int[] a = new int[100]; int i; for (i = 0; i < strs.length; i++) { a[i] = Integer.parseInt(strs[i]); } int x, y, z; if (i == 1) { x = a[0]; if (x <= 0) { System.out.println("0.00"); } else { rectangle d = new rectangle(x); System.out.println(two.format(d.area())); } } else if (i == 2) { x = a[0]; y = a[1]; if (x <= 0) { System.out.println("0.00"); } else { rectangle d = new rectangle(x, y); System.out.println(two.format(d.area1())); } } else if (i == 3) { for (i = 0; i < 3; i++) { for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { int max = a[j]; a[j] = a[j + 1]; a[j + 1] = max; } } } x = a[0]; y = a[1]; z = a[2]; if (x + y > z) { if (x <= 0) { System.out.println("0.00"); } else { rectangle d = new rectangle(x, y, z); System.out.println(two.format(d.area2())); } } else { System.out.println("0.00"); } } } } }