gpt4 book ai didi

java - 为什么我的构造函数参数没有传递?

转载 作者:行者123 更新时间:2023-12-02 02:11:33 24 4
gpt4 key购买 nike

这是我的类(class)。在底部的 main 方法中,我在构造函数中传递两个参数(int numTriangles,双半径)作为 (8,1)。在顶部 radius 和 numTriangles 声明的变量应采用这些值,因为我的构造函数分配它们然后运行计算。然而,当计算twoTheta时,我会得到除以零的错误,因为此时numTriangles为零。这是为什么?我该如何解决它?谢谢。

package Triangles;

public class Triangles {

double radius;
int numTriangles;
double twoTheta = 360/numTriangles;
double theta = twoTheta / 2;
double base;
double height;
double result;
double halfTriangleArea;
double triangleArea;
double area;

public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
runCalculation();
}

// My methods

public double calculateBase() { // SOH
double thetaToRadians = Math.toRadians(theta);
double base = Math.sin(thetaToRadians) / radius;
return base;
}

public double calculateHeight() { // CAH
double thetaToRadians = Math.toRadians(theta);
double height = Math.cos(thetaToRadians) / radius;
return height;
}

public double checkPythag(double base, double height) {
double a = base;
double b = height;
double result = Math.sqrt(a*a + b*b);
return result;
}

public double calculateArea(double base, double height) {
double halfTriangleArea = (0.5) * base * height;
return halfTriangleArea;
}

public double runCalculation() {
base = calculateBase();
height = calculateHeight();
result = checkPythag(base, height);
halfTriangleArea = calculateArea(base, height);
triangleArea = 2 * halfTriangleArea;
// C = Pi * D = Pi * 2 * r
// A = Pi * r.^2
area = numTriangles * triangleArea;
// Substitute Pi for X
// area = X * r.^2
// if r is 1
// area = X
return area;
}

// Runnable

public static void main(String[] args) { // create an instance of class to run in main
Triangles triangles = new Triangles(8, 1);
System.out.println("radius: " + triangles.radius);
System.out.println("numTriangles: " + triangles.numTriangles);
System.out.println("twoTheta " + triangles.twoTheta);
System.out.println("theta " + triangles.theta);
System.out.println("base: " + triangles.base);
System.out.println("height: " + triangles.height);
System.out.println("checkPythag " + triangles.result + " | " + triangles.radius);
System.out.println("halfTriangleArea: " + triangles.halfTriangleArea);
System.out.println("triangleArea: " + triangles.triangleArea);
System.out.println("Approximation of Pi by triangles: " + triangles.area);
}
}

最佳答案

正如多个答案所指出的,twoTheta(以及 theta)是在调用构造函数之前初始化的,因此会出现错误。

我建议您在构造函数内部初始化twoThetatheta

 public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
//Initialize twoTheta
this.twoTheta = 360/this.numTriangles;
this.theta = this.twoTheta/2;
runCalculation();
}

关于java - 为什么我的构造函数参数没有传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49935561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com