Java程序题,做的是那道必做题,急用,各位大神帮帮忙!!!
1个回答
展开全部
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
interface Shape{
double area() throws Exception;
void write(Object content);
}
abstract class AbstractShape implements Shape {
@Override
public void write(Object content) {
// TODO Auto-generated method stub
FileWriter fw = null;
BufferedWriter bw = null;
File file = null;
try {
file = new File("result.txt");
if (!file.exists())
file.createNewFile();
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(""+content);
bw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fw != null)
fw.close();
if(bw != null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Cricle extends AbstractShape {
private double r;
public Cricle() {
super();
}
public Cricle(double r) {
super();
this.r = r;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
@Override
public double area() throws Exception {
// TODO Auto-generated method stub
if (r <= 0) {
throw new Exception("半径不能小于0");
}
return Math.PI * Math.pow(r, 2);
}
}
class Rectangle extends AbstractShape {
private double w;
private double h;
public Rectangle() {
super();
}
public Rectangle(double w, double h) {
super();
this.w = w;
this.h = h;
}
public double getW() {
return w;
}
public void setW(double w) {
this.w = w;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
@Override
public double area() throws Exception {
// TODO Auto-generated method stub
if (w <= 0 || h <= 0) {
throw new Exception("不能构成矩形");
}
return w * h;
}
}
class Triangle extends AbstractShape {
private double x;
private double y;
private double z;
public Triangle() {
super();
}
public Triangle(double x, double y, double z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getZ() {
return z;
}
public void setZ(double z) {
this.z = z;
}
@Override
public double area() throws Exception {
// TODO Auto-generated method stub
if (x + y <= z || x + z <= y || y + z <= x) {
throw new Exception("不能构成三角形");
}
double p = (x + y + z) / 2;
return Math.sqrt(p * (p - x) * (p - y) * (p - z));
}
}
//测试
public class Test{
public static void main(String[] args) {
Shape shape = new Triangle(3, 4, 5);
try {
double area = shape.area();
shape.write(area);
System.out.println("area: " + area);
} catch (Exception e) {
e.printStackTrace();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |