Saturday, November 21, 2015

Java Program: Points In Three-dimensional Space

As is known to all, points in three-dimensional space can be expressed via space rectangular coordinates.There is a program, Point.java, in which I define a class named Point and do some simple operations on it.

//Point.java
public class Point
{
    int x, y, z; //3 coordinates of a point

    Point(int _x, int _y, int _z) //Constructor
    {
        x = _x;
        y = _y;
        z = _z;
    }

//To set the value of x, y and z coordinates
    void setx(int _x)
    {
        x = _x;
    }

    void sety(int _y)
    {
        y = _y;
    }

    void setz(int _z)
    {
        z = _z;
    }

//To calculate the square of distance between origin and the point
    int SquareOfDistance()
    {
        return x * x + y * y + z * z;
    }

//To test the program
    public static void main(String[] args)
    {
        Point point = new Point(3, 4, 5);

        System.out.println("The coordinate of this point is (" + point.x + "," + point.y + "," + point.z + "),and the square of distance between origin and the point is " + point.SquareOfDistance() + ".");
        point.setx(1);
        point.sety(2);
        point.setz(3);
        System.out.println("The coordinate of this new point is (" + point.x + "," + point.y + "," + point.z + "),and the square of distance between origin and the point is " + point.SquareOfDistance() + ".");
    }
}

The running results are following:

The coordinate of this point is (3,4,5),and the square of distance between origin and the point is 50.
The coordinate of this new point is (1,2,3),and the square of distance between origin and the point is 14.

Have you had a try?