我想提示用户三角形的三边。然后弄清楚三角形是直角三角形,等边形还是等腰形。但我的程序只是在错误处理中遇到错误并在尝试获取side(1)
时退出程序。所以我的问题是你看到我的代码导致了什么或出了什么问题?
驱动程序TestTriangle.java
public class TestTriangle {
public static void main(String[] args) {
System.out.println("Welcome to the Triangle Program");
System.out.println();
Triangle myTriangle = new Triangle();
myTriangle.buildTriangle();
System.out.println();
System.out.println("My analysis of this triangle is");
System.out.println();
myTriangle.classifyTriangle();
String prettyPerim = String.format("%.3g", myTriangle.perimeter());
String prettyArea = String.format("%.3g", myTriangle.area());
System.out.println("\tThe area of the triangle is " + prettyArea + ".");
System.out.println("\tThe perimeter of the triangle is " + prettyPerim + ".");
}
}
程序Triangle.java
import java.util.Scanner;
import java.util.InputMismatchException;
public class Triangle {
public static final double TOLERANCE = 0.0001;
private double min;
private double mid;
private double max;
private Scanner input;
public Triangle() {
double side1 = 0.0, side2 = 0.0, side3 = 0.0;
}
public void buildTriangle() {
double side1 = getSide(1);
double side2 = getSide(2);
double side3 = getSide(3);
// if side1 is greater than side2, the min is side1 and the max is side2
if (side1 < side2) {
min = side1;
max = side2;
// otherwise the min is side2 and the max is side1
} else {
min = side2;
max = side1;
}
// if side3 is less than the min value, then the mid value is the min value and the min value is side3
if (side3 < min) {
mid = min;
min = side3;
// if side3 is greater than the max value then the mid is the max and the max is side3
} else if (side3 > max) {
mid = max;
max = side3;
// otherwise the mid is side3
} else {
mid = side3;
}
}
public double getSide(int index) {
System.out.print("Please enter the length of side " + index + ": ");
double sideVal = 0.0;
try{
sideVal = input.nextDouble();
} catch (Exception e) {
System.out.println("You did not enter a valid input. Exiting.");
System.exit(1);
}
return sideVal;
}
public void classifyTriangle() {
// if the max value is greater than the min and the mid combined it is not a triangle, exit the program.
if (max > min + mid) {
System.out.println("Not a triangle");
System.exit(1);
}
else if (((Math.pow(min, 2)) + (Math.pow(mid, 2))) == (Math.pow(max, 2))) {
System.out.println("This is a right triangle");
}
else if (max == min || min == mid || max == mid) {
if (max == min && min == mid && max == mid) {
System.out.println("This is an equilateral triangle");
}
else {
System.out.println("This is an isosceles triangle");
}
}
}
public double perimeter() {
// calculate the perimeter
double perimeter = max + mid + min;
return perimeter;
}
public double area() {
// calculate the area
double semi = (max + mid + min) / 2;
double product = (semi - max) * (semi - mid) * (semi - min) * semi;
double area = Math.sqrt(product);
return area;
}
}
答案 0 :(得分:1)
您需要初始化您的输入
input = new Scanner(System.in);