这是初学者的问题。 我想修改计算多边形面积的程序。 多边形必须至少具有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));
}
}
答案 0 :(得分:0)
尝试一下:
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);
double sideNumber = 0;
while (sideNumber <= 2) {
System.out.println("Input the number of sides: ");
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));
}
}
当号码错误时,仍然会丢失其他消息。 祝您学习愉快:)
答案 1 :(得分:0)
您可以将输入代码包装在do-while中并循环,直到输入有效为止。
类似
input = new Scanner(System.in);
System.out.println("Input the number of sides: ");
boolean invalidInput = true;
do {
double sideNumber = input.nextDouble();
if(sideNumber > 2){
invalidInput = false;
}else{
System.out.println("Wrong number of sides!");
}
}while (invalidInput)
显然,您可以对其他输入执行相同的操作,并检查该值是否为正。
答案 2 :(得分:0)
我终于用boolean做到了,并执行while循环。谢谢。
public static void main(String[] args) {
double sideNumber;
input = new Scanner(System.in);
System.out.println("Input the number of sides: ");
boolean invalidInput = true;
do {
sideNumber = input.nextDouble();
if (sideNumber > 2) {
invalidInput = false;
} else
System.out.println("Wrong number of sides!");
} while (invalidInput);
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));