translate coordinate method java [closed] - java

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;
}

Related

Java - calculation distans and distans to origo - issue

I have forgot my old math from school.
I have made a java class that should calculate the distance between x,y,z and origo.
But have made a wrong turn somewhere and cant get out…
The calculation doesnt give the right value.
Can you help see what i have made wrong?
Its the distance calculation thats is wrong.
import java.io.PrintWriter;
import java.util.Scanner;
public class U3point {
public static void main(String[] args) {
System.out.println("Values for x,y,z ");
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out, true);
double x;
double y;
double z;
String[] koordinater = null;
String rad = in.nextLine();
System.out.println("toString: ");
while (!rad.equals("")) {
koordinater = rad.split("\\s");
x = Double.parseDouble(koordinater[0]);
y = Double.parseDouble(koordinater[1]);
z = Double.parseDouble(koordinater[2]);
Point p = new Point(x, y, z);
out.println(p);
//call method for origo
double d = p.getDistanceToOrigo();
System.out.println("Distance to Origo: " + d);
// call method for distance
double d2 = p.getDistanceTo(x, y, z);
System.out.println("Distance: " + d2);
System.out.println("Exit program with enter or new values");
rad = in.nextLine();
}
}
}
class Point {
private double x;
private double y;
private double z;
public Point(double x1, double y1, double z1) {
x = x1;
y = y1;
z = z1;
}
public void setX(double x1) {
x = x1;
}
public void setY(double y1) {
y = y1;
}
public void setZ(double z1) {
z = z1;
}
public double[] getCoordinates() {
return new double[] { x, y, z };
}
public double getDistanceTo(double x2, double y2, double z2) {
return (Math.sqrt(((x - x2) * (x - x2) + (y - y2) * (y - y2) + (z - z2) * (z - z2))));
}
public double getDistanceToOrigo()
{
return (Math.sqrt(((x) * (x) + (y) * (y) + (z) * (z))));
}
public String toString() {
return " x: =" + x + " y:=" + y + " z:=" + z;
}
}
The problem you were calculating the distance to the same point, here are an approach for you:
import java.io.PrintWriter;
import java.util.Scanner;
public class U3point {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out, true);
Point p1 = generatePoint();
Point p2 = generatePoint();
out.println(p1);
out.println(p2);
// call method for origo double
double d = p1.getDistanceToOrigo();
System.out.println("Distance to Origo: " + d);
// call method for distance
double d2 = p1.getDistanceTo(p2.getX(), p2.getY(), p2.getZ());
System.out.println("Distance: " + d2);
System.out.println("The end!!");
}
public static Point generatePoint() {
System.out.println("Values for x,y,z ");
String[] koordinater = null;
Scanner in = new Scanner(System.in);
String rad = in.nextLine();
Point p = null;
koordinater = rad.split("\\s");
double x = Double.parseDouble(koordinater[0]);
double y = Double.parseDouble(koordinater[1]);
double z = Double.parseDouble(koordinater[2]);
p = new Point(x, y, z);
return p;
}
}
class Point {
private double x;
private double y;
private double z;
public Point(double x1, double y1, double z1) {
x = x1;
y = y1;
z = z1;
}
public void setX(double x1) {
x = x1;
}
public void setY(double y1) {
y = y1;
}
public void setZ(double z1) {
z = z1;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
public double[] getCoordinates() {
return new double[] { x, y, z };
}
public double getDistanceTo(double x2, double y2, double z2) {
return (Math.sqrt(((x - x2) * (x - x2) + (y - y2) * (y - y2) + (z - z2) * (z - z2))));
}
public double getDistanceToOrigo() {
return (Math.sqrt(((x) * (x) + (y) * (y) + (z) * (z))));
}
public String toString() {
return " x: =" + x + " y:=" + y + " z:=" + z;
}
}
Output:
Values for x,y,z
1 2 3
Values for x,y,z
4 5 6
x: =1.0 y:=2.0 z:=3.0
x: =4.0 y:=5.0 z:=6.0
Distance to Origo: 3.7416573867739413
Distance: 5.196152422706632
The end!!

Variable values disappearing in Java

I'm making a rudimentary particle simulator in Java. For now, all I've done is make the particles atract each other with an equivalent to the electrical force. This part works fine (or at least as well as you would expect for such a basic model).
However, when I add a few particles, the program loses their values for position, velocity and acceleration, but does not lose other data (like, for example, their ID number). This does not always happens with the same amount of particles. Sometimes it happens when I add the fourth, fifth, second or third particle, but never with the first one. It always happens when I click to add a particle, and after it fails, I can no longer add anything (which is odd), and the particles don't move anymore (as you would expect, being their velocities and accelerations 0).
I am storing the particles in an ArrayList. The array does not lose the data (I've checked, the objects are in there, and I can even call their toString() method and retrieve their ID). The problem seems to be related to synchronization (given that it doesn't always happen at the same moment, it seems to be a bit random), but I can't figure out what it is.
I leave all the relevant code below.
public class Scene implements KeyListener, MouseListener, MouseMotionListener{
public static ArrayList<Particle> particleArray = new ArrayList<Particle>();
public static Object particleLock = new Object();
public void update() {
synchronized(particleLock) {
for(Particle particle: particleArray) {
double resultX = 0;
double resultY = 0;
for(int i = 0; i<particleArray.size(); i++) {
if(i != particleArray.indexOf(particle)) {
double[] result = PhysicsEngine.applyElectircalForce(particle, particleArray.get(i));
resultX += result[0];
resultY += result[1];
}
}
particle.netForceX = resultX;
particle.netForceY = resultY;
particle.update();
}
}
}
public void mousePressed(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
boolean positive = true;
if(e.getButton() == MouseEvent.BUTTON1) {
positive = true;
} else if(e.getButton() == MouseEvent.BUTTON3) {
positive = false;
}
synchronized(particleLock){
particleArray.add(new Particle(mouseX, mouseY, positive));
System.out.println("New particle added at " + mouseX + ", " + mouseY);
}
}
}
public class Particle{
public double x;
public double y;
public Point2D position;
public double velX;
public double velY;
public double acX;
public double acY;
private Color particleColor;
private int radius = 10;
// PHYSICS
public double mass;
public double charge;
public double netForceX;
public double netForceY;
private boolean positive;
public Particle(double x, double y, boolean positive) {
this.x = x - radius;
this.y = y - radius;
this.velX = 3;
this.velY = 2;
this.acX = 0;
this.acY = 0;
this.mass = 100;
this.positive = positive;
if(positive) {
this.charge = defaultCharge;
} else {
this.charge = defaultCharge*(-1);
}
this.position = new Point2D.Double(x, y);
particleColor = Color.WHITE;
}
public void update() {
acX = netForceX / mass;
acY = netForceY / mass;
velX += acX;
velY += acY;
if(x<=0 || x>=Simulation.WIDTH - 23){
velX = velX * -1;
x+= velX;
}
if(y<=0 || y>=Simulation.HEIGHT - 35){
velY = velY * -1;
y+= velY;
}
synchronized(Scene.particleLock) {
for(Particle otherPart: Scene.particleArray) {
if(otherPart.equals(this)) {
continue;
}
double distance = otherPart.position.distance(position);
if(distance <= radius + otherPart.radius) {
//aplicar lo que sé de choques de alguna manera
}
}
}
x+= velX;
y+= velY;
position.setLocation(x, y);
}
}
public class PhysicsEngine {
static double electricalConstant = 100000;
public static double[] applyElectircalForce(Particle thisPart, Particle otherPart) {
double distance = otherPart.position.distance(thisPart.position);
double angle = Math.asin(Math.abs(thisPart.y - otherPart.y)/distance);
double force = (electricalConstant * thisPart.charge * otherPart.charge)/Math.pow(distance, 2);
double forceX = force * Math.cos(angle);
double forceY = force * Math.sin(angle);
if(otherPart.x < thisPart.x) {
forceX = forceX*(-1);
}
if(otherPart.y < thisPart.y) {
forceY = forceY*(-1);
}
double[] result = {forceX, forceY};
return result;
}
}
I once had a similar problem with synchronization when I was working on an android project, try declaring particleArray volatile so that the compiler knows that particleArray will be changed on other or multiple threads. If that does not work I would suggest using a queue to push changes to the particle array from different threads and then pulling the intended changes to the array list in the update method to update your particle array list. In my experience changing values directly between different threads almost always causes problems.

Idiomatic Java: constraining data [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Playing with a simple Java Point class where I would like to constrain the X and Y values to be doubles that must be in the range -10 to 10, inclusive. I've written some code, but it's been years since I've written java and I would like to know if this is how it would be written in modern Java:
public class Point {
private double x;
private double y;
public Point(double x, double y) {
constrain("x", x);
constrain("y", y);
this.x = x;
this.y = y;
}
// is there a cleaner/shorter way of handling this, such as a direct way of declaring a
// subtype of double that I could use in method signatures?
protected static void constrain(String name, double val) {
if ( val < -10 || val > 10 ) {
throw new IllegalArgumentException(name + " must be between -10 and 10");
}
}
public double getX() { return x; }
public void setX(double x) {
constrain("x", x);
this.x = x;
}
public double getY() { return y; }
public void setY(double y) {
constrain("y", y);
this.y = y;
}
#Override
public String toString() {
return ("[" + x + "," + y + "]");
}
}
This is probably how I'd do it:
public class Point
{
private static final double X_MIN = -10.0, X_MAX = 10.0;
private static final double Y_MIN = -10.0, Y_MAX = 10.0;
private double x, y;
public Point(double x, double y) throws IllegalArgumentException
{
setX(x);
setY(y);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public void setX(double x) throws IllegalArgumentException
{
if (x < X_MIN || x > X_MAX)
{
throw new IllegalArgumentException("X out of range.");
}
this.x = x;
}
public void setY(double y) throws IllegalArgumentException
{
if (y < Y_MIN || y > Y_MIN)
{
throw new IllegalArgumentException("Y out of range");
}
this.y = y;
}
#Override
public String toString()
{
return String.format("[%.1f,%.1f]", x, y);
}
}
If the X and Y values are always from the same domain then you could encapsulate them in a class that does the checking for you:
class Coord {
private final double scalarValue;
public Coord(double scalarValue) throws IllegalArgumentException {
if (Math.abs(scalarValue) > MAX_COORD) {
throw new IllegalArgumentException("Coordinate out of range");
}
this.scalarValue = scalarValue;
}
public double getScalar() {
return scalarValue;
}
}
That puts the check in one place and allows you to expand coordinate functionality in the future without messing up your Point class. It also explicitly makes coordinates immutable which is likely to be a good idea (depending on use case).
Then your point constructor becomes:
public Point(Coord x, Coord y);

How to print return values from a boolean?

I am trying to print the value return value from a boolean, to check that the if statements are working correctly. I get no errors but nothing shows in the console. Any advice is appreciated.
Also if it makes a difference the code is not part of the main class. If it does, is there a way of printing the return value of the boolean from the main?
Here is what I have tried.
public boolean inCollision(double x, double y, furniture f) {
if (x + radius <= f.getXpos(0) || x + radius > f.getXpos(2)) {
System.out.println("False");
return false;
}
if (y + radius < f.getYpos(0) || y + radius > f.getYpos(2)) {
System.out.println("False");
return false;
}
System.out.println("True");
return true;
}
This is where furniture comes from
public class furniture {
private String name;
private double xpos;
private double ypos;
private double width;
private double height;
public furniture (String n, double x, double y, double w, double h)
{
name = n;
xpos = x;
ypos = y;
width = w;
height = h;
}
public double getXpos(int c){
if (c==0 || c==1){return xpos;}
else {return xpos+width;}
}
public double getYpos(int c){
if (c == 0 || c == 1){return ypos;}
else {return ypos+width;}
}
public String toString() {
return "the "+ name+ " has a height of "+height+" and a width of "+width+". Its coordinates are ("+xpos+","+ypos+")," ;
}
}
Below is the whole page of code for the first part.
public class roomba {
private double xpos;
private double ypos;
private double radius;
public roomba(double x, double y, double r){
xpos = x;
ypos = y;
radius = r;
}
public String toString() {
return "the coordinates of the roomba are ("+xpos+","+ypos+").It has a radius of "+radius ;
}
public boolean inCollision(double x, double y, furniture f){
if (x+radius <=f.getXpos(0) || x+radius >f.getXpos(2)){
System.out.println("False");
return false;
}
if (y+radius < f.getYpos(0) || y+radius > f.getYpos(2))
{
System.out.println("False");
return false;}
System.out.println("True");
return true;
}
In your main class you have to create two objects : roomba and furniture
roomba r = new roomba(1f,1f,1f);
furniture furn = new furniture("chair",2f,2f,2f,2f);
boolean retValBool = r.inCollision(1.5f,1.5f,furn); //
System.out.println(" inCollision method returns : " + retValBool);
In java you can handle for printing all primitive data types the same way. That means you can print integers, doubles , booleans etc with the same way :)

How to send an Object through a constructor?

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); }
}

Categories

Resources