开发者

A really simple Java question

开发者 https://www.devze.com 2022-12-17 05:20 出处:网络
I\'m trying to call angles from from the angle method down below in the Rotate90 method but I\'m not sure of the syntax. What is the correct syntax?

I'm trying to call angles from from the angle method down below in the Rotate90 method but I'm not sure of the syntax. What is the correct syntax?

import java.lang.Math;
public class CartesianPoint implements Point
{
    private double xCoord;
    private double yCoord;

  public CartesianPoint (double xCoordinate,double yCoordinate)
  {
      xCoord = xCoordinate;
      yCoord = yCoordinate;
  }

public double xCoordinate ()
 {
     return xCoord; 
 }

 public double yCoordinate ()
 {
     return yCoord;
 }

 public double angle ()
 {
    double angles;
    angles = Math.cos( xCoord / Math.sqrt( xCoord*xCoord + yCoord*yCoord)); 
    return angles;
 }

 public double radius ()
 {
    double 开发者_开发百科radius;
    radius = (yCoord*yCoord + xCoord*xCoord); //?
    return radius;
 }

public Point rotate90()
{
  double rotated;
  rotated = angles.angle + 90.0; //██████████ Error here ██████████
  return rotated;
}

public double distanceFrom(Point other)
{
  return 0;
}

}


I think you mean

rotated = angle() + 90.0;

Except I think you'll find that Math.cos uses radians not degrees, so you're not going to get the result you think you are. And shouldn't that be arc cos, not cosine? Something like this might be more what you're looking for:

public double angle()
{
  return Math.atan2(ycoord, xcoord) * 180 / Math.PI;
}

If you want rotate90 to return a new Point that is 90 degrees from the current point, then change it to the following:

   public Point rotate90()
   {
      return new CartesianPoint(-yCoord, xCoord);
   }


Method invocations in Java always have trailing parentheses even when they don't have any arguments:

rotated = angle() + 90.0;


Method call requires parenthesis even if there are no parameters needed. This is different from other languages, e.g.groovy.


To answer your question directly: If you want to be able to access the variable "angles" from outside the "angle" function, you must make it a class variable. That is, declare it outside of any function, like you have declared xCoord and yCoord. Then refer to it by its simple name without any reference to the function that created it.

Note that if rotate90 tries to reference angle before angles() is called, angle will contain zero (or whatever default value you set) and is unlikely to be useful.

It's not clear to me exactly what you're trying to accomplish. I think that your intent is that the angles function would take the arc cosine, not the cosine.

0

精彩评论

暂无评论...
验证码 换一张
取 消