Design a class named MyPoint to represent a point with x and y coordinates. The
ID: 3684524 • Letter: D
Question
Design a class named MyPoint to represent a point with x and y coordinates. The class contains: - Two data fields x and y that represent the coordinates. - A no-arg constructor that creates a point (0, 0). - A constructor that constructs a point with specified coordinates. - Two get methods for data fields x and y, respectively. - A method named distance that returns the distance from this point to another point of the MyPoint type. - A method named distance that returns the distance from this point to another point with specified x and y-coordinates. Draw the UML diagram for the class. Implement the class. Write a test program that creates two points (0, 0) and (10, 30.5) and displays the distance between them.
Explanation / Answer
package org.students;
import java.util.Scanner;
import java.awt.Point;
public class Distance {
private int pointX;
private int pointY;
public Distance(int x, int y)
{
pointX = x;
pointY = y;
}
public int getX()
{
return pointX;
}
public int getY()
{
return pointY;
}
public double getDistance(Distance otherPoint)
{
int x = pointX - otherPoint.pointX;
x = x * x;
int y = pointY - otherPoint.pointY;
y = y * y;
double ddistance = Math.sqrt(x + y);
return ddistance;
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the coordinates for point 1: (x and y) ");
int pointX = console.nextInt();
int pointY = console.nextInt();
Distance pointp1 = new Distance(pointX, pointY);
System.out.print("Enter the coordinates for point 2: (x and y) ");
int pointX2 = console.nextInt();
int pointY2 = console.nextInt();
Distance pointp2 = new Distance(pointX2, pointY2);
System.out.println("The Distance between the two points is: "
+ pointp1.getDistance(pointp2));
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
output:Enter the coordinates for point 1: (x and y) 4 5
Enter the coordinates for point 2: (x and y) 7 8
The Distance between the two points is: 4.242640687119285
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.