I am currently facing a problem and can't find the way. Here is the question...
Complete the Point class bellow:
public class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So that the following code produces the output bellow:
public class TestClass{
public static void testEqual(Point p1, Point p2){
if (p1.equals(p2)){
System.out.println("The two points are equal\n"+p1);
}else{
System.out.println("The two points are not equal");
System.out.println("First Point: "+ p1);
System.out.println("Second Point: " + p2);
}
}
public static void main(String [] args){
Point p1 = new Point(2,3);
Point p2 = Point.clonePoint(p1);
Point p3 = new Point(1,1);
Point p4 = new Point(2,3);
testEqual(p1,p2);
testEqual(p1,p3);
testEqual(p1,p4);
testEqual(p2,p4);
}
}
Outputs
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
The two points are not equal
First Point: The X Coordinate is 2 and the Y Coordinate is 3
Second Point: The X Coordinate is 1 and the Y Coordinate is 1
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
I can understand all the things but except this line Point p2 = Point.clonePoint(p1);
How can I solve it?
Add get methods for returning the point coordinates to your Point class:
public int getX()
{
return x;
}
public int getY()
{
return y;
}
Then add the following clonePoint() static method to your Point class:
public static Point clonePoint(Point p)
{
return new Point(p.getX(), p.getY());
}
Then add the following equals() method to your Point class:
public boolean equals(Point p)
{
return (p.getX() == getX()) && (p.getY() == getY());
}
This is all you need:
[note the last method 'clone' is a static (class) method that you access by prefixing it with the class name 'Point' followed by '.'].
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return "The X Coordinate is " + x + " and the Y Coordinate is " + y;
}
#Override
public boolean equals(Object otherPoint) {
if (this == otherPoint) return true;
if (otherPoint == null || getClass() != otherPoint.getClass()) return false;
Point point = (Point) otherPoint;
return x == point.x && y == point.y;
}
#Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
public static Point clonePoint(Point p) {
return p != null ? new Point(p.x, p.y) : null;
}
}
I think your homework wants you to add a cloning method to the Point class like this:
public class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public static Point clonePoint(Point p){ return new Point(p.x,p.y); }
}
Related
Rectangle is formed using on this test
#Test
public void testRectangle1() {
Point center = new Point(20, 30);
Rectangle rect = new Rectangle(center, 20, 20);
assertAll(
() -> assertEquals(10, rect.getTopLeft().getX()),
() -> assertEquals(20, rect.getTopLeft().getY()),
() -> assertEquals(30, rect.getBottomRight().getX()),
() -> assertEquals(40, rect.getBottomRight().getY()),
() -> assertEquals(20, rect.getWidth()),
() -> assertEquals(20, rect.getHeight())
);
}
I already have class for point it should work correctly i mostly add it for understanding.
public class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
this(0, 0);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void moveTo(int newX, int newY) {
x = newX;
y = newY;
}
public void moveRel(int dx, int dy) {
x += dx;
y += dy;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
So i stuck in second class for rectangle itself. First of all i kinda have hard time forming consructor that will form rectangle itself. And also on filling methods in rectangle class, as i have hard time in uderstanding what they should return becouse i have little experience in Java and coding.
public class Rectangle {
public int width = 0;
public int height = 0;
public Point center;
public Rectangle(Point center, int width, int height) {
int x = 0;
int y = 0;
width=x;
height=y;
}
public Point getTopLeft() {
Point point = new Point();
return point;
}
public Point getBottomRight() {
Point point = new Point();
return point;
}
public int getWidth() {
int x = 0;
return x;
}
public int getHeight() {
int y = 0;
return y;
}
}
In getTopLeft() and getBottomRight() you could create a point with center coordinates and then moveRel(int, int) it by width and height divided by 2, as you center point is in the middle of the both.
public Point getTopLeft() {
Point point = new Point(center.getX(), center.getY());
point.moveRel(- width / 2, height / 2);
return point;
}
public Point getBottomRight() {
Point point = new Point(center.getX(), center.getY());
point.moveRel(width / 2, - height / 2);
return point;
}
Constructor should write given values to the fields of the class.
Also consider using decimal type for the coordinates, only even height and width would be divisible by 2.
My plan is to create an array with only two values, which is {0,0} because I want to change its value in order to simulate how the coordinate moves.
I want to move the coordinate up to (0,1) when a random number is assigned to x,
let's say I have a line of if loop,
if(x=0){ //I would change the value from {0,0} to {0,1} }
I tried to write the code in this way,
public static int x = 0;
public static int y = 0;
public static void randomWalk(int [] moving_point) {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
moving_point[x,y] = moving_point[x,y+1];
}
}
but it is not correct,
is this a possible thing to do? and how?
Thank you!
The innermost code must be changed to:
moving_point[1] = moving_point[1] + 1;
The 1 gives you the index of the 'y' position in your moving_point array, but will not modify your fields.
public static int x = 0;
public static int y = 0;
public static void randomWalk(int [] moving_point) {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
moving_point[x,y] = moving_point[x,++y];
}
}
I would suggest to use Pre-Increment(++x) in this scenario. Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression.
moving_point[1]++;
inside the for.
I suggest you not to pass an array to the function since the method can't assume its length. You can either pass two ints or pass a class, there are severals already implemented: Point is just an example.
The arguably 'correcter' way to represent a Coordinate in Java is to create a Coordinate class:
public class Coordinate {
private int x;
private int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void moveUp(int distance) {
y += distance;
}
public void moveDown(int distance) {
y -= distance;
}
public void moveLeft(int distance) {
x -=distance;
}
public void moveRight(int distance) {
x += distance;
}
#Override
public String toString() {
return String.format("{%d,%d}", x, y);
}
}
public static void randomWalk(Coordinate point) {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
point.moveUp(1);
}
}
This allows you to succinctly represent multiple Coordinates in your software, as well as allowing you to write some very intuitive methods, such as the moveUp/Down/Left/Right in the above example.
Another good reason for doing this is that there are no constraints on your array, so someone could inadvertently add a third, fourth or fifth value, which clearly wouldn't make sense. Using a separate class makes the code more self-documenting.
Back to the example, you can now run:
Coordinate c = new Coordinate(0, 0);
System.out.println(c); // prints "{0,0}"
randomWalk(c);
System.out.println(c); // prints "{0,1}" IF you were lucky to get a random 0...
NB:
Here, Coordinate space is interpreted as like on a graph in school, increasing x to the right and increasing y going up. On computer screens the y-space is usually flipped (the origin is the top left of the screen), so as an exercise consider how you might correct that. (Hint, it only involves changingmoveUp() and moveDown())
Edit:
Following your comment, to be able to record the path, you'll probably want to use a LinkedHashMap instead of ArrayList (efficiency of lookups while keeping the ordering) and make Coordinate immutable by returning a new instance from each moveX operation. You will also need to implement equals() and hashCode().
public class Coordinate {
private final int x;
private final int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Coordinate moveUp(int distance) {
return new Coordinate(x, y+distance);
}
public Coordinate moveDown(int distance) {
return new Coordinate(x, y-distance);
}
public Coordinate moveLeft(int distance) {
return new Coordinate(x-distance, y);
}
public Coordinate moveRight(int distance) {
return new Coordinate(x+distance, y);
}
#Override
public String toString() {
return String.format("{%d,%d}", x, y);
}
#Override
public int hashCode() {
//we need to do something a bit more clever than "x+y", otherwise {1,0} might end up with the same hash as {0,1}
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if(getClass() != obj.getClass()) return false;
Coordinate other = (Coordinate)obj;
if(x != other.x) return false;
if(y != other.y) return false;
return true;
}
}
public class Walker {
private LinkedHashSet<Coordinate> path = new LinkedHashSet<>();
private Coordinate last;
public Walker(Coordinate startingPoint) {
path.add(startingPoint);
last = startingPoint;
}
public Set<Coordinate> getPath() {
return path;
}
public void randomWalk() {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
Coordinate nextStep = last.moveUp(1);
if(path.add(nextStep)) {
//Set returns "true" if the item was added, "false" otherwise.
last = nextStep;
} else {
//So if not added, we've already been there.
//take alternative action, retry, whatever...
}
}
}
}
Walker w = new Walker(new Coordinate(0,0));
for(int i=0; i<10; i++) {
w.randomWalk();
}
System.out.println(w.getPath());
I'm kind of new to Java, and trying to write a code that calculate the distance of two points 2 and 3, and scale of 10. Somehow, it does not work. Can you give me a hint, so I can fix the code?
import java.lang.Math;
public class Point {
int x, y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
public float scale(int factor) {
new Point(x * factor, y * factor);
return factor;
}
public float distance(){
double distance = Math.sqrt(x * x + y * y);
return distance;
}
public void main(String[] args) {
float p = new Point(2,3).scale(10);
System.out.println(distance);
}
}
In scale you are creating a new point with the scaled values and doing nothing with it. You're leaving x and y of the point in question untouched.
You probably mean to multiply x and y by factor, rather than creating a new point.
Also you're printing a variable named distance, which does not exist (so this probably doesnt even compile), rather than calling the method named distance() and printing its returned value.
public class Point {
int x, y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
public static Point scalePoint(Point p, int factor) { //scale a given point p by a given factor
Point scaledPoint = new Point(p.x * factor, p.y * factor); //by multipling the x and y value with the factor
return scaledPoint; //and return the new scaled point
}
public static double calculateDistance(Point p1, Point p2){ //to calculate the distance between two points
double distance = Math.sqrt(p1.x * p2.x + p1.y * p2.y); //send the two points as parameter to this method
return distance; //and return the distance between this two as a double value
}
public static void main(String[] args) {
Point p = new Point(2,3);
Point scaledPoint = scalePoint(p, 10);
double distance = calculateDistance(p, scaledPoint);
System.out.println(distance);
}
}
At the moment your distance method is calculating the distance of a point from the origin (i.e. point 0,0). It would make more sense if you made that explicit:
class Point {
private static final Point ORIGIN = new Point(0, 0);
private final int x;
private final int y;
public float distanceTo(Point other) {
float xDelta = other.x - this.x;
float yDelta = other.y - this.y;
return Math.sqrt(xDelta * xDelta + yDelta * yDelta);
}
public Point scale(float factor) {
return new Point(x * factor, y * factor);
}
}
Then finding the distance to the origin becomes point.distanceTo(Point.ORIGIN) which makes the intent clearer.
package Geometry;
public class TestGeometryPoint {
public static void main(String[] args) {
//Creates the object PointA and Assigns values
Point pA = new Point(); //PointA(0, 0)
pA.setX(2.0); //PointA(2.0, 0)
pA.setY(5.0); //PointA(2.0, 5.0)
//Creates the object PointB and Assigns values
Point pB = new Point(4.0, 6.1); //PointB(4.0, 6.1)
//Calculates the distance between PointA and PointB
double d = pA.distance(4.0, 6.1); //Distance from class to a set of coordinates
double dP = pA.distance(pB); //Distance from class to another point
double dPtP = Point.distance(pA, pB); //Distance from point to point
//Prints the result of the calculations
System.out.println("Distance between Point A & B: " + d);
System.out.println("Distance between Point A & B: " + dP);
System.out.println("Distance between Point A & B: " + dPtP);
}
}
This is my Test Class and my Point class below.
package Geometry;
public class Point {
//Initializes the coordinates for a point on a graph with the values of x and y
private static double x;
private static double y;
//Defualt Constructor
public Point() {
x = 0;
y = 0;
}
//Point Constructor
public Point(double x, double y) {
this.x = x;
this.y = y;
}
//Returns the x value
public double getX() {
return x;
}
//Changes the x value
public void setX(double x) {
Point.x = x;
}
//Returns the y value
public double getY() {
return y;
}
//Changes the y value
public void setY(double y) {
Point.y = y;
}
//Calculates the distance between the class's point coordinates and another set of point coordinates
public double distance(double x0, double y0) {
double distance = (Math.sqrt(((x0 - x) * 2.0) + ((y0 - y) * 2.0)));
return distance;
}
//Calculates the distance between the class's point and another Point class's location
public double distance(Point p) {
double distance = (Math.sqrt(((p.getX() - x) * (p.getX() - x)) + ((p.getY() - y) * (p.getY() - y))));
return distance;
}
//Calculates the distance between a Point class's location and another Point class's location
public static double distance(Point p1, Point p2) {
double distance = (Math.sqrt((Math.pow((p2.getX() - p1.getX()), 2.0) + (Math.pow((p2.getY() - p1.getY()), 2.0)))));
return distance;
}
}
d, dP, dPtP: all return 0.0 when compiled and run, but I have no idea why as I have tried changing code and checking my math when calculating distance. I think I might just need a new set of eyes to take a look at it.
I believe since your x and y variables are static, they belong to the class Point as a whole. When you create a Point(2,5);
You set the static variable of the class Point to be 2 and 5 and then, you create another Point(4,6) You set the same static value of x and y to be 4,6.
Therefore, comparing the distance between the same two Point are 0.
The right code for the class Point would be like so
public class Point {
//Initializes the coordinates for a point on a graph with the values of x and y
private double x;
private double y;
//Defualt Constructor
public Point() {
x = 0;
y = 0;
}
//Point Constructor
public Point(double x, double y) {
this.x = x;
this.y = y;
}
//Returns the x value
public double getX() {
return x;
}
//Changes the x value
public void setX(double x) {
this.x = x;
}
//Returns the y value
public double getY() {
return y;
}
//Changes the y value
public void setY(double y) {
this.y = y;
}
//Calculates the distance between the class's point coordinates and another set of point coordinates
public double distance(double x0, double y0) {
double distance = (Math.sqrt(((x0 - x) * 2.0) + ((y0 - y) * 2.0)));
return distance;
}
//Calculates the distance between the class's point and another Point class's location
public double distance(Point p) {
double distance = (Math.sqrt(((p.getX() - x) * (p.getX() - x)) + ((p.getY() - y) * (p.getY() - y))));
return distance;
}
//Calculates the distance between a Point class's location and another Point class's location
public static double distance(Point p1, Point p2) {
double distance = (Math.sqrt((Math.pow((p2.getX() - p1.getX()), 2.0) + (Math.pow((p2.getY() - p1.getY()), 2.0)))));
return distance;
Your problem is that you are confusing static and non-static fields.
By putting that little static on your field declarations you are saying: all instances of this class should be seeing the exact same variables.
So, when you create two points
p1 = new Point(5, 5);
p2 = new Point(10, 10);
the declaration of p2 "overrides" the 5-5 from p1 ... because, as said: all Points are using the same x and y.
Thus, solution: simply drop that keyword from the definition of x and y. Then each point has is very own x and y.
And, more importantly: understand that each and any character in your source code matters. This means: you better understand each and any concept that your source code is making use of!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I can't seem to get my transform method right. Any suggestions on how I could make the method translate the point better? i.e. when this method is invoked, it should be able to give the new point. Also I'm having issues creating the slope method...I know slope is y2-y1/x2-x1 but how would I make that into a method. Is there a Math class I can import for the slope? Thanks much appreciated
import java.util.*;
public class Point {
private int x; // to store variables for x & y
private int y;
private double slope;
//default constructor
public Point () {
double x = 0;
double y = 0;
}
//alternate constructor
public Point (double x1, double y1) {
double x = x1;
double y = y1;
}
//set coordinates
public void setCoord (double x1, double y1){
double x = x1;
double y = y1;
}
//print method
public void print () {
System.out.print(x + "," + y);
}
//toString Method
public String toString() {
return "(" + x + "," + y + ")";
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void equals () {
if (x==y)
System.out.println(" Coordinates are the same ");
else {
System.out.println(" Coordinates are different ");
}
}
public void copy(Point temp) {
x=temp.x;
y=temp.y;
}
public Point getCopy() {
Point temp = new Point();
temp.x = x;
temp.y = y;
return temp;
}
public void distanceFromOrigin(int x1, int y1) {
double dx = x-x1;
double dy = y-y1;
}
//calculate the distance from one point to another
public void distance (double x1, double y1) {
double distance = Math.sqrt((x * x1) + (y * y1));
}
//shift the location of a point by a given amount
public void transform (double dx, double dy) {
double transform = ((x+dx) (y+dy));
}
// returns true if any given point lines up horizontally with a given point.
public boolean isHorizontal () {
return true;
}
// returns true if any given point lines up vertically with a given point.
public boolean isVertical () {
return true;
}
// returns the slope of the line
public double slope() {
return slope;
}
}
public void equals (Object o) {
if(o instanceof Point) {
Point p = (Point)o;
return p.x == x && p.y == y;
} else {
return false;
}
}
public Point getCopy() {
return new Point(x, y);
}
public double slope(Point otherPoint) {
return ((double)(otherPoint.y - y)) / ((double)(otherPoint.x / x));
}
public double distance (Point otherPoint) {
double dx = otherPoint.x - x;
double dy = otherPoint.y - y;
return Math.sqrt((dx * dx) + (dy * dy));
}
public double distanceFromOrigin() {
return distance(new Point(0, 0));
}
public boolean isHorizontal (Point otherPoint) {
return otherPoint.y == y;
}
public boolean isVertical(Point otherPoint) {
return otherPoint.x == x;
}
public void transform (double dx, double dy) {
x += dx;
y += dy;
}