import java.util.Scanner;
public class Shape {
public static void main(String[]args) {
Shape s=new Shape();
Scanner sc=new Scanner(System.in);
System.out.println("输入随机生成图形个数:");
int N=sc.nextInt();
shape ss[]=new shape[N+1];
for(int i=0;i<N;i++){
System.out.println("输入图形:\n1:三角形\n2:圆形\n3:矩形");
int j=sc.nextInt();
switch(j) {
case 1:
{
int a,b,c;
do {
System.out.print("输入三角形三边:");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
if(a+b<=c||a+c<=b||b+c<=a) {
System.out.println("数据不合法,请重新输入!");
}
else break;
}while(true);
ss[i]=s.new Triangle(a,b,c);
break;
}
case 2:
{
System.out.print("输入圆的半径:");
int rr;
rr=sc.nextInt();
ss[i]=s.new Circle(rr);
break;
}
case 3:
{
System.out.print("输入矩形长和宽:");
int a,b;
a=sc.nextInt();
b=sc.nextInt();
ss[i]=s.new Rectangle(a,b);
break;
}
}
}
for(int i=0;i<N;i++) {
ss[i].Getsqual();
ss[i].Showsqual();
}
sc.close();
return;
}
public abstract class shape{
abstract void Getsqual();
public abstract void Showsqual();
}
public class Triangle extends shape{
double squal;
int l1,l2,l3;
public Triangle(int l1, int l2, int l3) {
super();
this.l1 = l1;
this.l2 = l2;
this.l3 = l3;
}
@Override
void Getsqual() {
double p=(l1+l2+l3)/2.0;
squal=Math.sqrt(p*(p-l1)*(p-l2)*(p-l3));
}
@Override
public void Showsqual() {
System.out.println("Triangle squal:"+squal);
}
}
public class Circle extends shape{
double squal;
int r;
public Circle(int r) {
super();
this.r = r;
}
@Override
void Getsqual() {
double PI=3.14159;
squal=PI*r*r;
}
@Override
public void Showsqual() {
System.out.println("Circle squal:"+squal);
}
}
public class Rectangle extends shape{
double squal;
int length,width;
public Rectangle(int length, int width) {
super();
this.length = length;
this.width = width;
}
@Override
void Getsqual() {
squal=length*width;
}
@Override
public void Showsqual() {
System.out.println("Rectangle squal:"+squal);
}
}
}
Java:实现抽象类形状,并派生出三角形,圆,矩形类
最新推荐文章于 2022-11-28 13:31:14 发布