Write a definition of a class named Point that can be used to store and manipula
ID: 3697834 • Letter: W
Question
Write a definition of a class named Point that can be used to store and manipulate the location of a point in the 2D plane. Provide a constructor to initialize the private data with default values. You will need to declare and implement the following member functions:
A) A member function set that sets the private data after an object of this class is created.
C) A member function to swap the X and Y values.
D) Two functions to retrieve the current coordinates of the point (one for X and Y).
Write a test program that requests data for several points from the user, creates the points, then calls the member functions.
Explanation / Answer
import java.io.*;
import java.util.*;
class Point {
private double x, y;
Point(double x_value, double y_value) {
x = x_value;
y = y_value;
}
public void swap() {
double temp = this.x;
this.x = this.y;
this.y = temp;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public static double distance(Point that) {
return Math.sqrt(that.getX() * that.getX() + that.getY() * that.getY());
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int i =0;
double x1,y1;
Point[] points = new Point[10];
while(i<10){
System.out.print("Enter x-coordinate: ");
x1 = input.nextInt();
System.out.print("Enter y-coordinate: ");
y1 = input.nextInt();
points[i] = new Point(x1,y1);
System.out.println("Distance from origin is: "+ distance(points[i]));
System.out.println("x-coordinate is: "+points[i].getX() +" and y-coordinate is: "+points[i].getY());
System.out.println("After Swaping the coordinates: ");
points[i].swap();
System.out.println("x-coordinate is: "+points[i].getX() +" and y-coordinate is: "+points[i].getY());
i++;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.