这是初学者的问题。我想修改计算多边形面积的程序。多边形必须至少有 3 个边。如何排除错误的数据输入?(1 面、0 面、-4 面等)
import java.util.Scanner;
public class Polygon {
private static Scanner input;
public static double polygonArea(double n, double s) {
// (n*s^2)/(4*tan(π/n))
return (n * s * s) / (4 * Math.tan(Math.PI / n));
}
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Input the number of sides: ");
double sideNumber = input.nextDouble();
// System.out.println("Wrong number of sides!");
System.out.println("Input the length of one of the sides: ");
double sideLenght = input.nextDouble();
input.close();
System.out.println("The area of a polygon is: " + polygonArea(sideNumber, sideLenght));
}
}
相关分类