我正在编写寻找Triangle区域的程序。但当我进入边长为1,1,1。那么面积就是0.0。所以要改变这个我用Math.ceil(area),方法得到最大整数值的答案。但仍然回答是0.0。还告诉我,即使我不使用Math.ceil()方法,那么area也应该具有值.97234,但它会自动显示值0.0。但对于其他情况,它工作正常。
import java.util.Scanner;
import java.util.InputMismatchException;
class Triangle1
{
static int counter=1; // keep track of the triangle no.
static int validTriangles=0; // calculate no. of valid triangles
static int unvalidTriangles=0; // calculate no. of unvalid triangles
String type; // stores the type of all triangles
int sides[]=new int[3]; // holds the length of sides of triangle
Scanner obj =new Scanner (System.in);
double area; // holds area
int perimeter; // holds perimeter
Triangle1 ()
{
area=0;
perimeter=0;
}
public void inputAndDetermine()
{
try
{
System.out.println("enter the length of first side of Triangle"+ " "+ counter +":");
sides[0]=obj.nextInt();
System.out.println("enter the length of second side of Triangle"+" " + counter + ":");
sides[1]=obj.nextInt();
System.out.println("enter the length of third side of Triangle"+" " + counter + ":");
sides[2]=obj.nextInt();
if(sides[0]<=0||sides[1]<=0||sides[2]<=0)
{
throw new Exception();
}
}
catch(NumberFormatException ex)
{
System.err.println("please enter length of side in numeric format , eg: 2");
}
catch(InputMismatchException ex)
{
System.err.println("please enter length of side in integer values , eg: 2");
}
catch(Exception ex)
{
System.err.println("Length of side can neither be negative nor zero, please enter value greter than zero");
}
if(((sides[0]+sides[1])>sides[2])&&((sides[1]+sides[2])>sides[0])&&((sides[0]+sides[2])>sides[1]))
{
type=determineType();
validTriangles++;
}
else
{ System.out.println("The Input lenghts of the sides doesn't describe a triangle.");
System.out.println("------------------------------------------------------------------------");
unvalidTriangles++;
type="N/A";
}
counter++;
}
public String determineType()
{
if(sides[0]==sides[1]&&sides[1]==sides[2])
{
return "Equilateral";
}
else if(sides[0]==sides[1]||sides[1]==sides[2]||sides[0]==sides[2])
{
return "Isoceles";
}
else
{
return "Scalene";
}
}
public void calculateArea()
{
double s=(sides[0]+sides[1]+sides[2])/2;
area = Math.sqrt(s*(s-sides[0])*(s-sides[1])*(s-sides[2]));
if (area<1)
{
area=Math.ceil(area);
}
else
{
area =Math.round(area*100d)/100d;
}
}
public void calculatePerimeter()
{
perimeter=sides[0]+sides[1]+sides[2];
}
public void displayResult()
{
System.out.println("the Triangle perimeter and area are:");
System.out.println(" "+ perimeter + "units, "+ area + "square units." + type);
System.out.println("------------------------------------------------------------------------");
}
}
问题出在calculateArea()方法中。