由于您正在学习 Java,因此开始尝试它的一些面向对象方面可能是一个好主意。您可以执行以下操作:
public class Triangle{
private int side1;
private int side2;
private int side3;
public Triangle(int side1, int side2, int side3){
this.side1=side1;
this.side2=side2;
this.side3=side3;
}
public boolean isValid(){
return side1>0 && side2>0 && side3>0;
}
public boolean isTriangle(){
return (side1+side2<=side3)
|| (side1+side3<=side2)
|| (side2+side3<=side1);
}
public static void main(String[] args){
try{
side1=Integer.parseInt(args[0]);
side1=Integer.parseInt(args[0]);
side1=Integer.parseInt(args[0]);
Triangle t=new Triangle(side1,side2,side3);
if(t.isValid() && t.isTriangle())
System.out.println("Yes this makes a valid triangle");
else System.out.println("Sorry this is not a valid triangle");
}
catch(NumberFormatException e){
System.out.println("Please make sure all arguments are numeric.");
}
}
}
更进一步,您还可以扩展此类以创建 RightTriangle 类。由于三角形边的字段是私有的,因此您需要在 Triangle 类中为每个边添加 getter 方法 (public int getSide1(){return side1;})。
public class RightTriangle extends Triangle{
public RightTriangle(int side1, int side2, int side3){
super(side1,side2,side3);
}
@Override
public boolean isValid(){
int a=getSide1();
int b=getSide2();
int c=getSide3();
return super.isValid()
&& ((a*a + b*b = c*c)
|| (a*a + c*c = b*b)
|| (b*b + c*c = a*a));
}
public static void main(String[] args){
//this is basically the same as the triangle class only now
//instantiate the RightTriangle class
RightTriangle rt=new RightTriangle(side1,side2,side3);
if(rt.isTriangle() && rt.isValid())
System.out.println("Yes this is a valid right triangle");
else System.out.println("sorry, this is not a right triangle");
}
}