[英]How do I define a java method in a class?
我真的希望有人可以帮助我,因为我一直坐着看着这个问题好几个小时,我认为这只是一个缺失的细节......但不确定。
我已经定义了一个三角形类,它应该采用3(x,y)坐标,并从中计算出边长,角和面积。 这个类看起来像这样:
public class Triangle {
private double x1, x2, x3, y1, y2, y3;
double sideA, sideB, sideC;
private double angleA, angleB, angleC;
public Triangle(double x1, double y1, double x2,
double y2, double x3, double y3) {
}
public double getSideA() {
return (Math.sqrt(Math.pow((x3-x2),2)+Math.pow((y3-y2),2)));
}
}
现在我想在我的Interaction类中调用我的getSideA方法。 我已经定义了我的坐标变量,并从扫描方法中获取了它们的值。 我还定义了一个变量sideA,我想从getSideA方法中获取值。 这就是我做到的方式:
Triangle userTriangle = new Triangle(x1, x2, x3, y1, y2, y3);
userTriangle.getSideA = sideA;
当我尝试编译Interaction类时,我得到以下错误代码:
Interaction.java:79: cannot find symbol
symbol : variable getSideA
location: class Triangle
userTriangle.getSideA = sideA;
^
我有什么想法吗?
分配和函数调用正在错误地执行。
sideA = userTriangle.getSideA();
^parens necessary when calling function
<---------- (value assigned from right to left)
分配从右到左进行。
此外,您的类中的私有变量未设置 。 你不会得到预期的结果。 使用,在构造函数中设置实例变量
this.<pvt_var> = value_passed_to_constructor;
鉴于x1
, x2
, x3
, y1
, y2
和y3
是变量并且已经赋值,你应该这样做:
Triangle userTriangle = new Triangle(x1, x2, x3, y1, y2, y3);
double sideA = userTriangle.getSideA();
在你的代码中, getSideA
是一个函数,所以你不能只调用userTriangle.getSideA
,你需要调用userTriangle.getSideA()
你想要得到sideA
,在这种情况下你应该写
sideA = userTriangle.getSideA()
要么你想要设置三角形的sideA
,在这种情况下你应该编写一个setSideA()
方法并像这样调用它:
userTriangle.setSideA(sideA)
首先,编译错误应该是
double sideA = userTriangle.getSideA();
你的构造函数也有问题。 应该是这样的
public Triangle(double x1, double y1, double x2, double y2, double x3, double y3)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
}
您必须在构造函数中设置x1,x2,x3,y1,y2,y3。
userTriangle.getSideA = sideA;
应该
sideA = userTriangle.getSideA();
userTriangle.getSideA = sideA;
是不正确的
尝试这个:
double sideA= userTriangle.getSideA();
构造函数应该是:
public Triangle(double x1, double y1, double x2, double y2, double x3, double y3)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.