Calculating distance between two points in 3D - java

My assignment is to create main class in which I initialize the value of any point to be at (0,0,0) and to be able to access and mutate all three values (x,y,z) individually. To do this I have used getters and setters. My next task is to create a method within my main class (which I shall call "distanceTo") that calculates the distance between two points.
How do I go about creating the method "distanceTo" that calculates the distance between two points by taking in the x,y,z coordinates ? I assume my answer will have something to do with sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2) but I do not know how I can write that in my method in my main class if my points are not defined until my second test point class
So far I only have two points, but I am looking for a more general answer (so that if I created three points, p1 p2 and p3, I could calculate the distance between p1 and p2 or the distance between p2 and p3 or the distance between p1 and p3.
My main class:
package divingrightin;
public class Point3d {
private double xCoord;
private double yCoord;
private double zCoord;
public Point3d(double x, double y, double z){
xCoord = x;
yCoord = y;
zCoord = z;
}
public Point3d(){
this (0,0,0);
}
public double getxCoord() {
return xCoord;
}
public void setxCoord(double xCoord) {
this.xCoord = xCoord;
}
public double getyCoord() {
return yCoord;
}
public void setyCoord(double yCoord) {
this.yCoord = yCoord;
}
public double getzCoord() {
return zCoord;
}
public void setzCoord(double zCoord) {
this.zCoord = zCoord;
}
//public double distanceTo(double xCoord, double yCoord, double zCoord ){
}
My class with the test points:
package divingrightin;
public class TestPoints {
public static void main(String[] args) {
Point3d firstPoint = new Point3d();
firstPoint.setxCoord(2.2);
firstPoint.setyCoord(1);
firstPoint.setzCoord(5);
//System.out.println(firstPoint.getxCoord());
Point3d secondPoint = new Point3d();
secondPoint.setxCoord(3.5);
secondPoint.setyCoord(22);
secondPoint.setzCoord(20);
}
}

As #Dude pointed out in the comments, you should write a method:
public double distanceTo(Point3d p) {
return Math.sqrt(Math.pow(x - p.getxCoord(), 2) + Math.pow(y - p.getyCoord(), 2) + Math.pow(z - p.getzCoord(), 2));
}
Then if you want to get the distance between 2 points you just call:
myPoint.distanceTo(myOtherPoint);
//or if you want to get the distance to some x, y, z coords
myPoint.distanceTo(new Point3d(x,y,z);
You could even make the method static and give it 2 points to compare:
public static double getDistance(Point3d p1, Point3d p2) {
return Math.sqrt(Math.pow(p1.getxCoord() - p2.getxCoord(), 2) + ...
}
P.S. my first answer :)

public double distanceTo(Point3d other) {
return Math.sqrt(Math.pow(this.xCoord-other.getxCoord(), 2)
+ Math.pow(this.yCoord-other.getyCoord(), 2)
+ Math.pow(this.zCoord-other.getzCoord(), 2));
}
Add this to your Point3d class. When you need to calculate the distance in the TestPoints class, you do something like
double distance = firstPoint.distanceTo(secondPoint);

You have two possible approaches, according to what you want to achieve.
You can put your "distanceTo" method inside the class Point3D:
public class Point3d {
...
public double distanceTo(Point3d ) {
return Math.sqrt( Math.pow(this.x - that.x, 2) + Math.pow(this.y - that.y, 2) + Math.pow(this.z - that.z, 2));
}
In this case, you are always using the first point as the first argument, and any other point as the one you want to compute the distance from.
Alternatively, you can have a generic distanceTo method that lives somewhere(such as in your Program class, where you have your main method), that takes two points and compute the distance between those:
public class Program {
static public void main(String[] args) {}
public double distanceTo(Point3d p1, Point3d p2) {
return Math.sqrt( Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2) + Math.pow(p1.z - p2.z, 2));
}
}
Which one is better? Depends on how you use them in the common case :)

Just use the getters
float distance = Math.sqrt(Math.pow(secondPoint.getXCoord() - firstPoint.getXCoord()), 2) + ...)

Two ideas.
Either add a:
public double distanceTo(Point3d otherPoint) {
// return distance by using this.getxCoord(), this.getyCoord(), etc.
// and otherPoint.getxCoord(), otherPoint.getyCoord()
}
method to your Point3d class.
Then, at the end of your main method, you can do:
System.out.println(firstPoint.distanceTo(secondPoint));
System.out.println(tenthPoint.distanceTo(ninthPoint));
Or, add a static method to your main TestPoints class:
public static double distanceBetween(Point3d point1, Point3d point2) {
// return distance by using point1.getxCoord(), etc. and point2.getxCoord()
}
Then, at the end of your main method, you can do:
System.out.println(distanceBetween(firstPoint, secondPoint));
System.out.println(distanceBetween(tenthPoint, ninthPoint));

Related

call a method in class, inheritance

I have a problem, the solution is probably very easy, but nothing comes to mind at the moment, so I am looking for a little help.
... so I have a problem with calling the method.
I have a Space 2D class:
public class Space2D {
//several other methods etc.
//for example I will take this method
public double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
and I want to call it in the SpaceTest class:
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D point2D = new Space2D();
// I also have a Space 3D class that inherits from the 2D class.
// but I want to call the distance method from the Space 2D class so I'll try to do it like this:
point2D.distance(3,4) // <-- wrong
}
}
I would like to put 3 and 4 after p1 and p2 from the distance method but I get a bug that I have to put integers in it if I want to do so, so my question what do I have to put in calling this method so that I can run it, i.e. what do I have to put for this object ?? "Space2D p1"?
point2D.distance (???)
Thank you in advance for your help and explanation, I hope you will help me understand this.
public double distance(Space2D p1, Space2D p2) {
...
This means when you invoke distance you have to pass in two objects of type Space2D.
point2D.distance(3,4) <-- wrong
You tried to invoke it with two integers, which is why you get the error. Points have an x and y coordinate, what does it even mean to ask for the distance between 3 and 4 if the domain is R2.
What you probably want is something like
int dist = point2d.distance(new Point2D(3,0), new Point2D(4,0));
That's because you're putting integers as parameter which is not allowing to take as parameter. Distance function takes distance(Space2D p1, Space2D p2) Space2D object.
You can use like this:
In Space2D Class :
public class Space2D {
private int x;
private int y;
public Space2D(int x, int y) {
this.x = x;
this.y = y;
}
//several other methods etc.
//for example I will take this method
public static double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
In SpaceTest class :
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D.distance(new Space2D(3, 2), new Space2D(3, 2));
}
}

How can I print multiple class instances in one statement? Java

public Class Point{
private double x;
private double y;
public Point() {
super();
}
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public static Point deepCopy(Point p2) {
Point point2 = new Point(p2.x+2, p2.y+2);
return point2;
}
public static Point shallowCopy(Point p4){
return p4;
}
public void setPoint3X(double x3) {
this.x = x+1;
}
public void setPoint3Y(double y3) {
this.y = y+1;
}
public void setPoint2(double x2, double y2) {
this.x = x2+2;
this.y = y2+2;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public class PointDemo {
public static void main(String[] args) {
double x = 0;
double y = 0;
Point point1 = new Point(5, 10);
Point point2 = Point.deepCopy(point1);
Point point3 = Point.deepCopy(point2);
point3.setPoint3X(x);
point3.setPoint3Y(y);
Point point4 = new Point();
point4 = Point.shallowCopy(point3);
Question 4 -
Write a class called Point. The class has two instance fields: x and y, both are of double type.
Write two constructors: one that uses x and y values for a point, and the other uses the first point values to create a second Point object with the exact same x and y values. Write a Demo class to build the following four Point objects.
Point 1: (x=5, y=10)
Point 2: (x=7, x=12). This point needs to be built using the deep copy constructor that copies point 1 and then using only one setter method.
Point 3: (x=10, y=15). This point needs to be built using the deep copy method that uses Point 2 as the original and then using two setter methods to change the required x and y values.
Point 4: This point needs to be built using the shallow copy method and it must use Point 3 as the shallow copy template.
Finally print all four points using one statement.
Okay. So my code gives me all the values from point1-point4 however, I cannot figure out a way to print them all in one statement. Obviously a loop in the demo class can print every Point object but that would be multiple print statements which violates the one print statement requirement.
Also, I cannot use an array in the Point class because it violates the 2 fields requirement.
Can anybody help or give me a suggestion as to how I can take all the Point objects and print it in one statement? Or is that even possible and maybe I am reading the question wrong?
You can use PrintStream.format(format(String format, Object... args):
System.out.format("(%f, %f), (%f, %f), (%f, %f), (%f, %f)\n", point1.x, point1.y, point2.x, point2.y, ...and so on);
I'm going to post this as an answer too since I think it might be what your instructor actually wants.
The key point here is to remember that the toString() method on your class can be used like a regular string and concatenate other strings, and that's what you normally do with + when calling println(). So just use the normal println() method like you've probably been doing already.
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
You can use streams:
Arrays.stream(new Point[] {point1, point2, point3, point4}).forEach(System.out::println);
or String.format()
System.out::println(String.format("%s %s %s %s", point1, point2, point3, point4));

Problems with setters and getters in java program dealing with circles

I have been assigned the following task for an introductory java course:
You should write a class that represents a circle object and includes the following:
Private class variables that store the radius and centre coordinates of the object.
Constructors to create circle objects with nothing supplied, with just a radius value supplied and with a radius and centre coordinates supplied.
Public instance methods that allow the radius and centre coordinates to be set and retrieved (often known as set/get methods).
Public instance methods that return the circumference and area of the circle.
A public class method that tests if two circle objects overlap or not
Here is my code:
import java.lang.Math;
public class Circle {
private double xCentre, yCentre, Radius;
// constructors
public Circle() {
xCentre = 0.0;
yCentre = 0.0;
Radius = 1.0;
}
public Circle(double R) {
xCentre = 0.0;
yCentre = 0.0;
Radius = R;
}
public Circle(double x, double y, double R) {
xCentre = x;
yCentre = y;
Radius = R;
}
//getters
public double getX() {
return xCentre;
}
public double getY() {
return yCentre;
}
public double getRadius() {
return Radius;
}
//setters
public void setX(double NewX) {
xCentre = NewX;
}
public void setY(double NewY) {
yCentre = NewY;
}
public void setRadius(double NewR) {
Radius = NewR;
}
//calculate circumference and area
public double Circumference() {
return 2*Math.PI*Radius;
}
public double Area() {
return Math.PI*Radius*Radius;
}
//determine overlap
public static double Overlap(Circle c1, Circle c2) {
double xDelta = c1.getX() - c2.getX();
double yDelta = c1.getY() - c2.getY();
double separation = Math.sqrt(xDelta*xDelta + yDelta*yDelta);
double radii = c1.getRadius() + c2.getRadius();
return separation - radii;
}
}
}
and
import java.io.Console;
public class cp6 {
public static void main(String args[]){
//Set up the Console
Console myConsole = System.console();
//Declare cirlce
Circle first = new Circle(2.0,4.0,6.0);
myConsole.printf("Circumference of first circle is ", first.Circumference(), "\n");
myConsole.printf("Area of first circle is ", first.Circumference(), "/n");
first.setRadius(2);
first.setX(2);
first.setY(2);
myConsole.printf("New X of first circle is ", first.getX(), "/n");
myConsole.printf("New Y of first circle is ", first.getY(), "/n");
myConsole.printf("New Radius of first circle is ", first.getRadius(), "/n");
Circle second = new Circle(-1.0,3.0,5.0);
Circle third = new Circle(1,1,1);
if (Circle.Overlap(second, third) <= 0) {
myConsole.printf("Second and third circles overlap");
}
else {
myConsole.printf("Second and third circles do not overlap");
}
myConsole.printf("New Y of first circle is ", first.getY());
Calculate and print out distance between them using the class method
myConsole.printf("Distance between first and second is : %.5g\n", Circle.Overlap(first, second));
}
}
The second program just has to demonstrate each aspect addressed in the brief I pasted at the top and I've only a rough idea of how to do this so if what I'm doing seems stupid to any of you please offer suggestions of what else I can do.
Your problem is that you're using the Console.printf() method incorrectly.
The first parameter to this method should be a format, and it has to have placeholders inside it for the other parameters. Read up on it in The Java Platform documentation. In fact, you should familiarize yourself with the Java platform documentation. You need to use it often to make sure you're calling methods correctly or what methods are available in a given class.
So, your printout lines should actually have been:
myConsole.printf("Circumference of first circle is %.2f%n", first.Circumference());
myConsole.printf("Area of first circle is %.2f%n", first.Area());
...etc.
The format %.2f means "The corresponding parameter is a floating-point number. Display it with a precision of 2 digits after the decimal point". The %n replaces your "\n" - the whole "template" of the print should be just in the format string. And in this type of format, one should use %n instead of \n.
I'm not sure why you opted for using the system console rather than the usual System.out.println(). If you choose to go with System.out, there is also a printf() method there that works exactly as Console.printf() - the first parameter is a format, the others are embedded in it.
One last comment: there are conventions when writing Java code:
Indent your code properly
Class names' first letter is always uppercase.
Non-constant fields and local variable names' first letter is always lowercase.
Method names also start with a lowercase letter.

Loss of precision calculating degrees from two points

I have made a class Location which allows to set, change a location (coordinates x,y , the limits are decided by xMin,xMax,yMin,yMax), to caluculate the distance between two points, and to get the direction from another location.
The direction is in degress (in [0,2pi]) from another location.
The direction goes from North (assuming that North is the pole oriented where there are higher coordinates), in clockwise order.
package TruckingCompany;
public class Location
{
private double x;
private double y;
private static final double xMax=1000.0;
private static final double xMin=-1000.0;
private static final double yMax=1000.0;
private static final double yMin=-1000.0;
public Location()
{
setX(0.0);
setY(0.0);
}
public Location(double x,double y)
{
setX(x);
setY(y);
}
public Location(Location location)
{
setX(location.getX());
setY(location.getY());
}
public void setX(double x)
{
if(x>=xMin && x<=xMax)
this.x=x;
}
public void setY(double y)
{
if(y>=yMin && y<=yMax)
this.y=y;
}
public void set(double x,double y)
{
setX(x);
setY(y);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getDistanceFrom(Location from)
{
double dx,dy;
dx=from.getX()-x;
dy=from.getY()-y;
return Math.sqrt(Math.pow(dx, 2.0)+Math.pow(dy, 2.0));
}
public double getDirectionFrom(Location from)
{
double dy=from.getY()-y;
double direction=Math.PI/4 - Math.asin (Math.toRadians(dy/getDistanceFrom(from)));
if(Double.isNaN(direction)==false)
{
if(from.getX()-x<0.0)
direction+=Math.PI/2;
if(dy<0.0)
direction+=Math.PI;
}
return direction;
}
#Override
public String toString()
{
return "(" + x + " , " + y + ")";
}
}
The problem is the the precision, for example I try to calculate the distance from these two locations:
Location l1,l2;
l1=new Location(0.0,0.0);
l2=new Location(300.0,300.0);
System.out.print(Math.toDegrees(l1.getDirectionFrom(l2)));
The problem is the precision: in this example it prints 44.29 degrees, it should be 45.0, why a so huge loss of precision?
You're near 45 degrees, which means you're going to be operating close to maxima and minima for some trig functions. I'd check the steps and see if you're getting an intermediate result very close to 0.
Try replacing the call to pow with dx*dx and dy*dy.
Break this up with intermediate results.
Use Math.atan2(deltaX, deltaY) to calculate the angle of a vector in radians. It returns answers all the way from 0 to 2 * Math.PI without having to do casework depending on the signs of the inputs.

A really simple Java question

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.

Categories

Resources