Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a java method in a class?

I really hope someone can help me, as I've been sitting and looking at this problem for hours and I think it's just a detail that is missing...but not sure.

I have defined a class Triangle which is supposed to take 3 (x,y) coordinates and from it, calculate sidelengths, corners and area. The class looks like this:

   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)));
        }
    }

Now I want to call my getSideA method in my Interaction class and. I have defined my coordinate variables and they get their values from scan method. I have also defined a variable sideA, that I want to get the value from my getSideA method. This is how I have done it:

Triangle userTriangle = new Triangle(x1, x2, x3, y1, y2, y3);   

 userTriangle.getSideA = sideA;

When I try to compile the Interaction class I get the following error code:

Interaction.java:79: cannot find symbol
symbol  : variable getSideA
location: class Triangle
     userTriangle.getSideA = sideA;
                 ^

Any ideas what I am doing wrong??

like image 984
user1088537 Avatar asked Sep 18 '26 18:09

user1088537


1 Answers

Assignment & function invocation are being performed incorrectly.

sideA =  userTriangle.getSideA();
                               ^parens necessary when calling function

    <---------- (value assigned from right to left)

Assignment occurs from right to left.


Also, private variables in your class are not being set. You won't end up with the expected result. Set the instance variables within the constructor, using

this.<pvt_var> = value_passed_to_constructor;
like image 129
Anirudh Ramanathan Avatar answered Sep 21 '26 08:09

Anirudh Ramanathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!