图形面积计算

题目来源:学堂在线_清华大学_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());
			}
		}
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值