【问题标题】:Java code - area of a polygonJava 代码 - 多边形的面积
【发布时间】:2014-12-31 01:41:51
【问题描述】:

我有一些没有编译错误的代码,但是当我在运行时输入第二个数字后它在我身上崩溃:(

这是我所拥有的:

import java.util.Scanner;
public class Assignment536 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the number of sides: ");
    int numberOfSides = input.nextInt();
    System.out.println("Enter the side: ");
    double side = input.nextInt();

    System.out.println("The area of the polygon is: " +area(numberOfSides, side));

    input.close();

}

public static double area(int n, double side) {
    double answer = (n*(side*side))*(4*(Math.tan((Math.PI*n))));
    return answer;
}

}

任何帮助将不胜感激! 谢谢, 塞巴斯蒂安

【问题讨论】:

  • 解释“Crashes on me”是什么意思。如果您收到错误消息,请将整个错误消息放在您的问题中。

标签: java eclipse methods polygon area


【解决方案1】:

公式的最后一部分是错误的。它应该是 (Math.pi/n) 。

import java.util.Scanner;

public class CalcAreaPolygon {

    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);

        double area; 
        final double PI;   /method in the formula
        double side;  
        int n;

        PI = Math.PI;

        System.out.println("Enter the number of sides: ");
        n = scanner.nextInt();

        scanner.nextLine();

        System.out.println("Enter the side: ");
        side = scanner.nextDouble();

        area = (n * (side * side)) / (4 * (Math.tan(PI/n)));

        System.out.println("The area of the polygon is " + area);

    }

}

【讨论】:

    【解决方案2】:

    你应该改变:

    final double side = input.nextInt();
    

    为

    final double side = input.nextDouble();
    

    如果你想读一个双精度。

    【讨论】:

      【解决方案3】:

      在numberOfSlices 和side 请求之间添加input.nextLine()...

      System.out.println("Enter the number of sides: ");
      int numberOfSides = input.nextInt();
      input.nextLine();
      System.out.println("Enter the side: ");
      double side = input.nextInt();
      

      请求numberOfSlices 后,input 缓冲区中仍有回车/换行,当您尝试请求side 值时,Scanner 失败,因为它无法转换回车/行馈送到double 类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-13
        • 2014-06-03
        • 2013-10-24
        • 2013-11-22
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多