In: Computer Science
in java Create a class City with x and y as the class variables. The constructor with argument will get x and y and will initialize the city. Add a member function getDistanceFrom() to the class that gets a city as the input and finds the distance between the two cities.
class City {
private int x;
private int y;
//constryctor to initialize the values
public City(int aX, int aY) {
super();
x = aX;
y = aY;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
//calculates distance using sqrt(x2-x1^2 +
y2-y1^2)
public double getDistanceFrom(City c) {
return Math.sqrt(Math.pow(c.getX()
- getX(), 2) + Math.pow(c.getY() - getY(), 2) * 1.0);
}
}
public class TestCity {
public static void main(String[] args) {
City c1 = new City(3, 4);
City c2 = new City(4, 3);
System.out.println(c1.getDistanceFrom(c2));
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me