【问题描述】
输入三角形的三边长,计算面积和周长。
类中有构造方法、关于属性的set、get方法、计算面积和周长的方法。如果输入的边长不能构成三角形,则对象会拒绝接受该值,并输出相应的错误信息。
如果构造方法中提供的三边不能构成三角形,则三边都赋值为0。
根据已有源代码和输出结果,填写代码空白处,使程序完整。
【输入形式】
三角形的三边长度。
【输出形式】
三角形的面积和周长,或者还包含错误信息。
【样例输入①】
3 4 5
【样例输出①】
perimeter=12.0
area=6.0
a=3.0,b=4.0,c=5.0
a=6.0,b=6.0,c=6.0
a input error
a=6.0,b=6.0,c=6.0
b input error
a=6.0,b=6.0,c=6.0
c input error
a=6.0,b=6.0,c=6.0
【样例输入②】
100 120 150
【样例输出②】
perimeter=370.0
area=5981.168364124187
a=100.0,b=120.0,c=150.0
a=103.0,b=122.0,c=151.0
a=123.0,b=122.0,c=151.0
a=123.0,b=142.0,c=151.0
a=123.0,b=142.0,c=171.0
【样例输入③】
1 2 3
【样例输出③】
perimeter=0.0
area=0.0
a=0.0,b=0.0,c=0.0
a b c input error
a=0.0,b=0.0,c=0.0
a input error
a=0.0,b=0.0,c=0.0
b input error
a=0.0,b=0.0,c=0.0
c input error
a=0.0,b=0.0,c=0.0
【评分标准】
程序通过得满分。不完全正确得部分分数。
注:因为网上找不到答案,所以自己写了一下。
代码:
package test;
import java.util.Scanner;
public class Triangle {
private double a, b, c;
double getArea() {
double p = (this.a + this.b + this.c) / 2;
return Math.sqrt(p * (p - this.a) * (p - this.b) * (p - this.c));
}
double getPerimeter() {
return this.a + this.b + this.c;
}
void setSide(double x, double y, double z) {
if((x+y)<=z||(z+y)<=x||(x+z)<=y)
{
System.out.println("a b c input error");
this.a=0;
this.b=0;
this.c=0;
}
else {
this.a = x;
this.b = y;
this.c = z;
}
}
double getA() {
return this.a ;
}
double getB() {
return this.b ;
}
double getC() {
return this.c ;
}
Triangle(double x,double y,double z) {
if((x+y)<=z||(z+y)<=x||(x+z)<=y) {
this.a=this.b=this.c=0;
}
else
{
this.a=x;
this.b=y;
this.c=z;
}
}
void setA(double x) {
if((x+this.b)<=this.c||(this.b+this.c)<=x||(x+this.c)<=this.b)
{ System.out.println("a input error");
}
else
this.a=x;
}
void setB(double y)
{
if((this.a+y)<=this.c||(y+this.c)<=this.a||(this.a+this.c)<=y)
{
System.out.println("b input error");
}
else
this.b=y;
}
void setC(double z)
{
if(((this.a+this.b)<=z)||((this.b+z)<=this.a)||((this.a+z)<=this.b)) {
System.out.println("c input error");
}
else
this.c=z;
}
public String toString() {
return "a="+this.a+",b="+this.b+",c="+this.c;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double x = in.nextDouble();
double y = in.nextDouble();
double z = in.nextDouble();
Triangle t = new Triangle(x, y, z);
System.out.println("perimeter=" + t.getPerimeter());
System.out.println("area=" + t.getArea());
System.out.println(t);
t.setSide(t.getA() + 3, t.getB() + 2, t.getC() + 1);
System.out.println(t);
t.setA(t.getA() + 20);
System.out.println(t);
t.setB(t.getB() + 20);
System.out.println(t);
t.setC(t.getC() + 20);
System.out.println(t);
in.close();
}
}