3D point Learn programming Java

Lesson:

OOP More On Classes


Exercise:

3D point


Objetive:

Create a class "Point3D", to represent a point in 3-D space, with coordinates X, Y and Z. It must contain the following methods:

MoveTo, which will change the coordinates in which the point is.
DistanceTo(Point3D p2), to calculate the distance to another point.
ToString, which will return a string similar to "(2,-7,0)"
And, of course, getters and setters.

The test program must create an array of 5 points, get data for them, and calculate (and display) the distance from the first point to the remaining four ones.


Code:

public class Main
{
	protected double x, y, z;


	public Point3D()
	{
	}

	public Point3D(double nx, double ny, double nz)
	{
		MoveTo(nx, ny, nz);
	}

	public final double GetX()
	{
		return x;
	}

	public final void SetX(double value)
	{
		x = value;
	}

	public final double GetY()
	{
		return y;
	}

	public final void SetY(double value)
	{
		y = value;
	}

	public final double GetZ()
	{
		return z;
	}

	public final void SetZ(double value)
	{
		z = value;
	}

	public final void MoveTo(double nx, double ny, double nz)
	{
		x = nx;
		y = ny;
		z = nz;
	}

	public final double DistanceTo(Point3D p2)
	{
		return Math.sqrt((x - p2.GetX()) * (x - p2.GetX()) + (y - p2.GetY()) * (y - p2.GetY()) + (z - p2.GetZ()) * (z - p2.GetZ()));
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.