write a java program . Create a class named Point. It should have instance varia
ID: 3777331 • Letter: W
Question
write a java program .
Create a class named Point. It should have instance variables x and y of type double whose values define the location of a point on the x-y plane. Include a constructor with no parameters that assigns 0.0 to x and y. Include a second constructor with two parameters that sets the values of x and y to whatever values you pass the constructor. Your class should have a method named distanceFromOrigin that returns the distance of the point defined by x and y from the origin (i.e., the point (0.0, 0.0)).
Your class should also have a second method toString that returns a string representing the values of x and y. For example, if x and y are both 1.0, then toString shouldreturnthestring"(1.0, 1.0)".Test your program with the following main method:
public static void main(String[] args)
{
Point p = new Point();
System.out.println(p.toString() + " is this far from origin: " + p.distanceFromOrigin());
p = new Point(3, 4);
System.out.println(p.toString() + " is this far from origin: " + p.distanceFromOrigin());
}
(Hint: The distance of the point (x, y) from (0.0, 0.0) is the square root of the sum of the squares of x and y. To determine the square root of a double value, call the method Math.sqrt, passing it the value for which you need the square root. This method will then return the square root as a double value. For example, to find the square root of the value in sum and assign it to d, use
d = Math.sqrt(sum);
sqrt is a static method in the Math class. Thus, it is called via the name of its class.)
Explanation / Answer
Point.java
public class Point {
//Declaring instance variables
private double x;
private double y;
//Zero Argumented constructor
public Point() {
super();
this.x=0;
this.y=0;
}
//Parameterized constructor
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
//This method will calculate the distance from origin
public double distanceFromOrigin()
{
return Math.sqrt(Math.pow(x, 2)+Math.pow(y, 2));
}
//toString() method will display the contents of an object inside it.
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
______________________
TestPoint.java
public class TestPoint {
public static void main(String[] args) {
//Creating a Point class object
Point p = new Point();
//Displaying the distance from origin
System.out.println(p.toString() + " is this far from origin: " + p.distanceFromOrigin());
//Creating a Point class object
p = new Point(3, 4);
//Displaying the distance from origin
System.out.println(p.toString() + " is this far from origin: " + p.distanceFromOrigin());
}
}
________________________
Output:
(0.0,0.0) is this far from origin: 0.0
(3.0,4.0) is this far from origin: 5.0
_____________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.