public Class Point{
private double x;
private double y;
public Point() {
super();
}
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public static Point deepCopy(Point p2) {
Point point2 = new Point(p2.x+2, p2.y+2);
return point2;
}
public static Point shallowCopy(Point p4){
return p4;
}
public void setPoint3X(double x3) {
this.x = x+1;
}
public void setPoint3Y(double y3) {
this.y = y+1;
}
public void setPoint2(double x2, double y2) {
this.x = x2+2;
this.y = y2+2;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public class PointDemo {
public static void main(String[] args) {
double x = 0;
double y = 0;
Point point1 = new Point(5, 10);
Point point2 = Point.deepCopy(point1);
Point point3 = Point.deepCopy(point2);
point3.setPoint3X(x);
point3.setPoint3Y(y);
Point point4 = new Point();
point4 = Point.shallowCopy(point3);
Question 4 -
Write a class called Point. The class has two instance fields: x and y, both are of double type.
Write two constructors: one that uses x and y values for a point, and the other uses the first point values to create a second Point object with the exact same x and y values. Write a Demo class to build the following four Point objects.
Point 1: (x=5, y=10)
Point 2: (x=7, x=12). This point needs to be built using the deep copy constructor that copies point 1 and then using only one setter method.
Point 3: (x=10, y=15). This point needs to be built using the deep copy method that uses Point 2 as the original and then using two setter methods to change the required x and y values.
Point 4: This point needs to be built using the shallow copy method and it must use Point 3 as the shallow copy template.
Finally print all four points using one statement.
Okay. So my code gives me all the values from point1-point4 however, I cannot figure out a way to print them all in one statement. Obviously a loop in the demo class can print every Point object but that would be multiple print statements which violates the one print statement requirement.
Also, I cannot use an array in the Point class because it violates the 2 fields requirement.
Can anybody help or give me a suggestion as to how I can take all the Point objects and print it in one statement? Or is that even possible and maybe I am reading the question wrong?
You can use PrintStream.format(format(String format, Object... args):
System.out.format("(%f, %f), (%f, %f), (%f, %f), (%f, %f)\n", point1.x, point1.y, point2.x, point2.y, ...and so on);
I'm going to post this as an answer too since I think it might be what your instructor actually wants.
The key point here is to remember that the toString() method on your class can be used like a regular string and concatenate other strings, and that's what you normally do with + when calling println(). So just use the normal println() method like you've probably been doing already.
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
You can use streams:
Arrays.stream(new Point[] {point1, point2, point3, point4}).forEach(System.out::println);
or String.format()
System.out::println(String.format("%s %s %s %s", point1, point2, point3, point4));
Related
This question already has answers here:
Operator overloading in Java
(10 answers)
Closed 5 years ago.
I have the following class, which describe one point on XY surface:
class Point{
double x;
double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So I want to overlad + and - operators to have possibility write run following code:
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)
How can I do it in Java? Or I should use methods like this:
public Point Add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y);
}
Thanks in advance!
You cannot do this in Java. You'd have to implement a plus or add method in your Point class.
class Point{
public double x;
public double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public Point add(Point other){
this.x += other.x;
this.y += other.y;
return this;
}
}
usage
Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b); //=> (3,3)
// because method returns point, you can chain `add` calls
// e.g., a.add(b).add(c)
Despite you can't do it in pure java you can do it using java-oo compiler plugin.
You need to write add method for + operator:
public Point add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
and java-oo plugin just desugar operators to these method calls.
There is no operator overloading in Java. Apparently for reasons of taste. Pity really.
(Some people will claim that Java does have overloading, because of + with String and perhaps autoboxing/unboxing.)
Let's talk about value types.
Many early classes (and some later ones) make a right mess of this. Particularly in AWT. In AWT you should be explicitly making copies of simple values all over the place. Almost certainly you want to make value types immutable - the class should be final and it should never change state (generally all final fields pointing to effective immutables).
So:
public final class Point {
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public static of(int x, int y) {
return new Point(x, y);
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point add(Point other) {
return of(x+other.x, y+other.y);
}
// Standard fluffy bits:
#Override public int hashCode() {
return x + 37*y;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return x==other.x && y==other.y;
}
#Override public String toString() {
return "("+x+", "+y+")";
}
}
The original code was confused between int and double, so I've chosen one. If you used double you should exclude NaN. "Point" tends to imply an absolute point, which doesn't make sense to add. "Vector" or "dimension" would probably be more appropriate, depending upon what you intend.
I've hidden the constructor, as identity is not important. Possibly values could be cached. Possibly it is, say, common to add a point to a zero point, so no points need to be created.
It's possible you might want a mutable version, for example to use as an accumulator. This should be a separate class without an inheritance relationship. Probably not in simple cases, but I'll show it anyway:
public final class PointBuilder {
private int x;
private int y;
public PointBuilder() {
}
public PointBuilder(Point point) {
this.x = point.x;
this.y = point.y;
}
public Point toPoint() {
return new Point(x, y);
}
public PointBuilder x(int x) {
this.x = x;
return this;
}
public PointBuilder y(int y) {
this.y = y;
return this;
}
public PointBuilder add(Point other) {
this.x += other.x;
this.y += other.y;
return this;
}
}
You cannot do this in Java because there is no operator overloading in Java.
You have to use the second option you have mentioned:
Edit: You can add the Add method in the Point class itself
public Point Add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
You cannot overload operators in java. You will need handle this in Point class.
You cannot override operators in Java. That's one of the reasons why any nontrival math (especially geometric) operations should not be implemented in Java (the Point class above is kind of such a class, if you want it to do some real work, for example a line-line intersection, you'd better do it in C++).
public class Point{
private double x;
private double y;
public Point (double x, double y) {
this.x = x;
this.y = y;
}
public double getX () {
return this.x;
}
public double getY () {
return this.y;
}
// distance returns the distance between this point and a given point
public double distance (Point p) {
return Math.sqrt ((p.x - this.x) * (p.x - this.x) +
(p.y - this.y) * (p.y - this.y));
}
public String toString(){
return "[" + this.x +","+this.y +"]";
}
public static Point nearestPoint(Point[] points, Point point){
Point p = points[0];
for(int i = 0; i < points.length; i++){
if(points[i].distance(point) < p.distance(point)){
p = points[i];
}
}
return p;
}
public static void main(String[] args){
Point[] points = {new Point(1,2),
new Point(2,3),
new Point(5,2)};
Point point = new Point (1,2);
Point nearestPoint = nearestPoint(points,point);
System.out.println(nearestPoint);
}
}
Task 1
A static method, nearestPoint , accepts an array of points (objects of type Point ) and one point (an object of type
Point ), and returns that point in the array which is closest to the given point. Create that method.
Task 2
Create an array of points (objects of type Point ) and a point (an object of type Point ).
Use the method nearestPoint to determine the point in the array that is closest to the given point.
Question:In Task 1, have I implemented the method nearestPoint correctly as it's asked in the task description?
should i declare an array of of object inside that method instead of Point p.
This is the output [1.0,2.0] and I'm not sure that this is the correct result?
Any hints , tip suggestion would be great.
Yes. Your implementation seems fine according to your description of nearestPoint method under Task 1. However, you can start your for loop variable i from 1 instead of 0 since you check for distance of the given point from first point in the array in the very first iteration.
public static Point nearestPoint(Point[] points, Point point) {
Point p = points[0];
for (int i = 1; i < points.length; i++) {
if (points[i].distance(point) < p.distance(point)) {
p = points[i];
}
}
return p;
}
Your output is also fine since any point is closest to itself.
I am writing a method in the class "CartesianPoint" that finds the distance between two Cartesian points. Whenever I call this, the distance that is printed out is always zero, no matter which points I use. I believe that the new point I create to find the distance is somehow overriding my instance variables in point, but I don't know how to correctly code this.
Here is the CartesianPoint Class:
public class CartesianPoint implements Point {
private static double x;
private static double y;
public CartesianPoint(double xCoord, double yCoord){
x = xCoord;
y = yCoord;
}
public double xCoordinate(){
return x;
}
public double yCoordinate(){
return y;
}
public double radius(){
double radius = Math.sqrt(Math.pow(xCoordinate(), 2)+Math.pow(yCoordinate(), 2));
return radius;
}
public double angle(){
double angle = Math.acos(xCoordinate() / radius());
return angle;
}
public double distanceFrom(Point other){
//System.out.println("x coordinate of this: " + xCoordinate());
//System.out.println("x coordinate of other: " + other.xCoordinate());
double xDistance = x - other.xCoordinate();
double yDistance = y - other.yCoordinate();
double distance = Math.sqrt(Math.pow(xDistance, 2) - Math.pow(yDistance, 2));
return distance;
}
//not currently being used
public Point rotate90(){
Point rotatedPoint = new CartesianPoint(0, 0);
return rotatedPoint;
}
}
Here is the method call in my tester class:
public class tester{
public static void main(String[] args){
Point p = new CartesianPoint(3, 4);
Point a = new CartesianPoint(6, 7);
System.out.println("Cartesian: (" + p.xCoordinate() + ", " + p.yCoordinate() + ")");
System.out.println("Polar: (" + p.radius() + ", " + p.angle() + ")");
System.out.println("Distance: " + p.distanceFrom(a));
}
}
And this is the output I am getting:
Cartesian: (6.0, 7.0)
Polar: (9.219544457292887, 0.8621700546672264)
Distance: 0.0
To clarify, Cartesian and Polar should be printing out the coordinates of 'p', not 'a' like they are doing right now. It seems like every new point created is overriding the coordinates of the last point.
Any help on this is greatly appreciated!
Remove the static keyword before declaring CartesianPoint's properties:
private double x;
private double y;
Then you'll be sure you're accessing the right properties to each instance of the class (encapsulating the properties).
Also, the formula you're using to get the distance between the two points is incorrect, it should have been
double distance = Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
As the formula is sqrt((xb - xa)2 + (yb - ya)2), the correct method would be:
public double distanceFrom(Point other){
//System.out.println("x coordinate of this: " + xCoordinate());
//System.out.println("x coordinate of other: " + other.xCoordinate());
double xDistance = x - other.xCoordinate();
double yDistance = y - other.yCoordinate();
double distance = Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
return distance;
}
Hint: check the formula for calculating the distance (e.g. see here) and compare it with what you have written here:
Math.sqrt(Math.pow(xDistance, 2) - Math.pow(yDistance, 2));
Do you see the difference?
Hint #2: Minus???
When you write some code that doesn't work correctly, it pays to:
Read what you have written carefully
Check the requirements.
Check your domain knowledge: in this case "the math"
My assignment is to create main class in which I initialize the value of any point to be at (0,0,0) and to be able to access and mutate all three values (x,y,z) individually. To do this I have used getters and setters. My next task is to create a method within my main class (which I shall call "distanceTo") that calculates the distance between two points.
How do I go about creating the method "distanceTo" that calculates the distance between two points by taking in the x,y,z coordinates ? I assume my answer will have something to do with sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2) but I do not know how I can write that in my method in my main class if my points are not defined until my second test point class
So far I only have two points, but I am looking for a more general answer (so that if I created three points, p1 p2 and p3, I could calculate the distance between p1 and p2 or the distance between p2 and p3 or the distance between p1 and p3.
My main class:
package divingrightin;
public class Point3d {
private double xCoord;
private double yCoord;
private double zCoord;
public Point3d(double x, double y, double z){
xCoord = x;
yCoord = y;
zCoord = z;
}
public Point3d(){
this (0,0,0);
}
public double getxCoord() {
return xCoord;
}
public void setxCoord(double xCoord) {
this.xCoord = xCoord;
}
public double getyCoord() {
return yCoord;
}
public void setyCoord(double yCoord) {
this.yCoord = yCoord;
}
public double getzCoord() {
return zCoord;
}
public void setzCoord(double zCoord) {
this.zCoord = zCoord;
}
//public double distanceTo(double xCoord, double yCoord, double zCoord ){
}
My class with the test points:
package divingrightin;
public class TestPoints {
public static void main(String[] args) {
Point3d firstPoint = new Point3d();
firstPoint.setxCoord(2.2);
firstPoint.setyCoord(1);
firstPoint.setzCoord(5);
//System.out.println(firstPoint.getxCoord());
Point3d secondPoint = new Point3d();
secondPoint.setxCoord(3.5);
secondPoint.setyCoord(22);
secondPoint.setzCoord(20);
}
}
As #Dude pointed out in the comments, you should write a method:
public double distanceTo(Point3d p) {
return Math.sqrt(Math.pow(x - p.getxCoord(), 2) + Math.pow(y - p.getyCoord(), 2) + Math.pow(z - p.getzCoord(), 2));
}
Then if you want to get the distance between 2 points you just call:
myPoint.distanceTo(myOtherPoint);
//or if you want to get the distance to some x, y, z coords
myPoint.distanceTo(new Point3d(x,y,z);
You could even make the method static and give it 2 points to compare:
public static double getDistance(Point3d p1, Point3d p2) {
return Math.sqrt(Math.pow(p1.getxCoord() - p2.getxCoord(), 2) + ...
}
P.S. my first answer :)
public double distanceTo(Point3d other) {
return Math.sqrt(Math.pow(this.xCoord-other.getxCoord(), 2)
+ Math.pow(this.yCoord-other.getyCoord(), 2)
+ Math.pow(this.zCoord-other.getzCoord(), 2));
}
Add this to your Point3d class. When you need to calculate the distance in the TestPoints class, you do something like
double distance = firstPoint.distanceTo(secondPoint);
You have two possible approaches, according to what you want to achieve.
You can put your "distanceTo" method inside the class Point3D:
public class Point3d {
...
public double distanceTo(Point3d ) {
return Math.sqrt( Math.pow(this.x - that.x, 2) + Math.pow(this.y - that.y, 2) + Math.pow(this.z - that.z, 2));
}
In this case, you are always using the first point as the first argument, and any other point as the one you want to compute the distance from.
Alternatively, you can have a generic distanceTo method that lives somewhere(such as in your Program class, where you have your main method), that takes two points and compute the distance between those:
public class Program {
static public void main(String[] args) {}
public double distanceTo(Point3d p1, Point3d p2) {
return Math.sqrt( Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2) + Math.pow(p1.z - p2.z, 2));
}
}
Which one is better? Depends on how you use them in the common case :)
Just use the getters
float distance = Math.sqrt(Math.pow(secondPoint.getXCoord() - firstPoint.getXCoord()), 2) + ...)
Two ideas.
Either add a:
public double distanceTo(Point3d otherPoint) {
// return distance by using this.getxCoord(), this.getyCoord(), etc.
// and otherPoint.getxCoord(), otherPoint.getyCoord()
}
method to your Point3d class.
Then, at the end of your main method, you can do:
System.out.println(firstPoint.distanceTo(secondPoint));
System.out.println(tenthPoint.distanceTo(ninthPoint));
Or, add a static method to your main TestPoints class:
public static double distanceBetween(Point3d point1, Point3d point2) {
// return distance by using point1.getxCoord(), etc. and point2.getxCoord()
}
Then, at the end of your main method, you can do:
System.out.println(distanceBetween(firstPoint, secondPoint));
System.out.println(distanceBetween(tenthPoint, ninthPoint));
I have been assigned the following task for an introductory java course:
You should write a class that represents a circle object and includes the following:
Private class variables that store the radius and centre coordinates of the object.
Constructors to create circle objects with nothing supplied, with just a radius value supplied and with a radius and centre coordinates supplied.
Public instance methods that allow the radius and centre coordinates to be set and retrieved (often known as set/get methods).
Public instance methods that return the circumference and area of the circle.
A public class method that tests if two circle objects overlap or not
Here is my code:
import java.lang.Math;
public class Circle {
private double xCentre, yCentre, Radius;
// constructors
public Circle() {
xCentre = 0.0;
yCentre = 0.0;
Radius = 1.0;
}
public Circle(double R) {
xCentre = 0.0;
yCentre = 0.0;
Radius = R;
}
public Circle(double x, double y, double R) {
xCentre = x;
yCentre = y;
Radius = R;
}
//getters
public double getX() {
return xCentre;
}
public double getY() {
return yCentre;
}
public double getRadius() {
return Radius;
}
//setters
public void setX(double NewX) {
xCentre = NewX;
}
public void setY(double NewY) {
yCentre = NewY;
}
public void setRadius(double NewR) {
Radius = NewR;
}
//calculate circumference and area
public double Circumference() {
return 2*Math.PI*Radius;
}
public double Area() {
return Math.PI*Radius*Radius;
}
//determine overlap
public static double Overlap(Circle c1, Circle c2) {
double xDelta = c1.getX() - c2.getX();
double yDelta = c1.getY() - c2.getY();
double separation = Math.sqrt(xDelta*xDelta + yDelta*yDelta);
double radii = c1.getRadius() + c2.getRadius();
return separation - radii;
}
}
}
and
import java.io.Console;
public class cp6 {
public static void main(String args[]){
//Set up the Console
Console myConsole = System.console();
//Declare cirlce
Circle first = new Circle(2.0,4.0,6.0);
myConsole.printf("Circumference of first circle is ", first.Circumference(), "\n");
myConsole.printf("Area of first circle is ", first.Circumference(), "/n");
first.setRadius(2);
first.setX(2);
first.setY(2);
myConsole.printf("New X of first circle is ", first.getX(), "/n");
myConsole.printf("New Y of first circle is ", first.getY(), "/n");
myConsole.printf("New Radius of first circle is ", first.getRadius(), "/n");
Circle second = new Circle(-1.0,3.0,5.0);
Circle third = new Circle(1,1,1);
if (Circle.Overlap(second, third) <= 0) {
myConsole.printf("Second and third circles overlap");
}
else {
myConsole.printf("Second and third circles do not overlap");
}
myConsole.printf("New Y of first circle is ", first.getY());
Calculate and print out distance between them using the class method
myConsole.printf("Distance between first and second is : %.5g\n", Circle.Overlap(first, second));
}
}
The second program just has to demonstrate each aspect addressed in the brief I pasted at the top and I've only a rough idea of how to do this so if what I'm doing seems stupid to any of you please offer suggestions of what else I can do.
Your problem is that you're using the Console.printf() method incorrectly.
The first parameter to this method should be a format, and it has to have placeholders inside it for the other parameters. Read up on it in The Java Platform documentation. In fact, you should familiarize yourself with the Java platform documentation. You need to use it often to make sure you're calling methods correctly or what methods are available in a given class.
So, your printout lines should actually have been:
myConsole.printf("Circumference of first circle is %.2f%n", first.Circumference());
myConsole.printf("Area of first circle is %.2f%n", first.Area());
...etc.
The format %.2f means "The corresponding parameter is a floating-point number. Display it with a precision of 2 digits after the decimal point". The %n replaces your "\n" - the whole "template" of the print should be just in the format string. And in this type of format, one should use %n instead of \n.
I'm not sure why you opted for using the system console rather than the usual System.out.println(). If you choose to go with System.out, there is also a printf() method there that works exactly as Console.printf() - the first parameter is a format, the others are embedded in it.
One last comment: there are conventions when writing Java code:
Indent your code properly
Class names' first letter is always uppercase.
Non-constant fields and local variable names' first letter is always lowercase.
Method names also start with a lowercase letter.