题目来源:学堂在线_清华大学_JAVA程序设计
我们有一些图形的边长数据,这些图形包括三角新和矩形,请你编写一个程序求出它们的面积。
请你实现一个基础图形类Graph,然后实现三角形类Triangle和矩形类Rectangle,继承自Graph。根据输入的边数实现不同的对象,并计算面积。
输入格式:
一行,一个整数n,表示图形个数。
n行,每行是用空格隔开的整数。
输出格式:
n行,每行是一个图形的面积。
输入样例:
2
5 5
6 6 6
输出样例:
25
15
package chapter03;
import java.util.Scanner;
abstract class Graph{
abstract int getS();
}
class Triangle1 extends Graph{
double a;
double b;
double c;
Triangle1(int a,int b,int c){
this.a = a;
this.b = b;
this.c = c;
}
public int getS() {
double p = (a+b+c)/2;
return (int) Math.floor(Math.sqrt(p*(p-a)*(p-b)*(p-c)));
}
}
class Rectangle1 extends Graph{
double a;
double b;
Rectangle1(double a,double b){
this.a = a;
this.b = b;
}
public int getS() {
return (int) Math.floor(a*b);
}
}
public class test02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = Integer.parseInt(input.nextLine().trim());
for (int i=0;i<n;i++) {
String s = input.nextLine().trim();
String[] t = s.split(" ");
if (t.length == 3) {
int a = Integer.parseInt(t[0]);
int b = Integer.parseInt(t[1]);
int c = Integer.parseInt(t[2]);
Triangle1 tri = new Triangle1(a,b,c);
System.out.println(tri.getS());
}
else if (t.length == 2) {
int a = Integer.parseInt(t[0]);
int b = Integer.parseInt(t[1]);
Rectangle1 rec = new Rectangle1(a,b);
System.out.println(rec.getS());
}
}
}
}