I'm half way through an assignment in java where I have two classes and need to calculate a x- and y-position. I get half of the tests correct but can't seem to get the two last ones correct. Could you perhaps guide my in the right direction?
I have one class calle Point and one PointMain. I get the arguments in PointMain and need to create the right methods in Point. I can't make any changes in the class PointMain as I got that from the assignment.
Class Point:
public class Point {
private int x = 0;
private int y = 0;
public Point() {
}
public Point(int xPoint, int yPoint) {
x = xPoint;
y = yPoint;
}
public String toString() {
return x + "," + y;
}
public double distanceTo(Point p2) {
double avstand = Math.sqrt(((p2.x*1 - p2.x*2) * (p2.x*1 - p2.x*2)) + ((p2.y*1 - p2.y*2) * (p2.y*1 - p2.y*2)));
return avstand;
}
public void move(int iPoint, int jPoint) {
x = x + iPoint; // I have a problem with this that it doesn't add
y = y + jPoint; // the 3,4 that I got from p2 with the 5,-2.
}
public void moveToXY(int xTag, int yTag) {
}
public boolean isEqualTo(Point p2) { //And I'm not really sure on how to
return false; //construct this method either...
}
}
Class PointMain:
public class PointMain {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(3,4);
System.out.println(p1.toString()); // ==> (0,0)
System.out.println(p2.toString()); // ==> (3,4)
if (p1.isEqualTo(p2)) // False!
System.out.println("The two points are equal");
double dist = p1.distanceTo(p2);
System.out.println("Point Distance: "+dist);
p2.move(5,-2); // ==> (8,2)
p1.moveToXY(8,2); // ==> (8,2)
System.out.println(p1);
System.out.println(p2);
if (p1.isEqualTo(p2)) // True!
System.out.println("The two points are equal");
}
}
First of all you should add getters
public int getX()
{
return x;
}
public int getY()
{
return y;
}
Than implement isEqual
public boolean isEqualTo(Point p2) {
return x == p2.getX() && y == p2.getY();
}
you can also declare x and y public and then there is no need for getters and code is simpler as you can see in implementation of java.awt.Point.
I don't see problem with "move" function.
And last
public void moveToXY(int xTag, int yTag) {
x = xTag;
y = yTag;
}
For additional info you can lookup how java.awt.Point implemented, and work on your function parameters naming iPoint/jPoint is horrible names
For the equality method, think that in which condition the two points are equal. Consider using if for validating the condition and getters for getting the points x and y.
And I don't see any problem with the move method.
And as #Juniar said in the comments, there's another problem in your distanceTo method. You want to get x and y of p2 but they are private variables so you can't have them by this way. In this case your are having the x and y of the object which the method is called on. So the output won't be desirable. (see getters again)
Related
So, I have a class that contains two numbers, more exactly X and Z. I'm storing it on a TreeMap, that needs the key class implement Comparable. The problem is, how am I going to compare the X and Z to other class on the compareTo() method?
I have already tried to add up the X and Z integers for the both classes and comparing them with Integer.compare(), but this is not a good solution because if X and Z are switched, it will end on the same result.
public class Position2D implements Comparable<Position2D> {
private int x, z;
#Override
public int compareTo(Position2D position2D) {
int coordinatesSum = this.getX() + this.getZ();
int otherCoordinatesSum = position2D.getX() + position2D.getZ();
return Integer.compare(coordinatesSum, otherCoordinatesSum);
}
}
Solved with:
#Override
public int compareTo(#Nonnull Position2D position2D) {
int xComparison = Integer.compare(this.getX(), position2D.getX());
int zComparison = Integer.compare(this.getZ(), position2D.getZ());
return xComparison != 0 ? xComparison : zComparison;
}
Special thanks to #harold.
I am trying to create a Vector class for use with LuaJ. The end goal is to have the user not write much lua, and have most of the work done on my Java engine.
As my understanding goes, I need to set the metatable for the lua representation of my Java vector class? The problem I am having though, is that when I am trying to overwrite some metatable functionality it doesn't seem to have any affect in my lua script. What I am trying to do now is overwrite the + operator, so I can add two vectors together or add a vector by a constant.
Here is my Vector class so far:
package math;
import org.luaj.vm2.*;
import org.luaj.vm2.lib.*;
import org.luaj.vm2.lib.jse.*;
public class Vector3Lua {
public float X;
public float Y;
public float Z;
public Vector3Lua unit;
static {
// Setup Vector class
LuaValue vectorClass = CoerceJavaToLua.coerce(Vector3Lua.class);
// Metatable stuff
LuaTable t = new LuaTable();
t.set("__add", new TwoArgFunction() {
public LuaValue call(LuaValue x, LuaValue y) {
System.out.println("TEST1: " + x);
System.out.println("TEST2: " + y);
return x;
}
});
t.set("__index", t);
vectorClass.setmetatable(t);
// Bind "Vector3" to our class
luaj.globals.set("Vector3", vectorClass);
}
public Vector3Lua() {
// Empty
}
// Java constructor
public Vector3Lua(float X, float Y, float Z) {
this.X = X;
this.Y = Y;
this.Z = Z;
this.unit = new Vector3Lua(); // TODO Make this automatically calculate
System.out.println("HELLO");
}
// Lua constructor
static public class New extends ThreeArgFunction {
#Override
public LuaValue call(LuaValue arg0, LuaValue arg1, LuaValue arg2) {
return CoerceJavaToLua.coerce(new Vector3Lua(arg0.tofloat(), arg1.tofloat(), arg2.tofloat()));
}
}
// Lua Function - Dot Product
public float Dot(Vector3Lua other) {
if ( other == null ) {
return 0;
}
return X * other.X + Y * other.Y + Z * other.Z;
}
// Lua Function - Cross Product
public LuaValue Cross(Vector3Lua other) {
Vector3Lua result = new Vector3Lua( Y * other.Z - Z * other.Y,
Z * other.X - X * other.Z,
X * other.Y - Y * other.X );
return CoerceJavaToLua.coerce(result);
}
}
Here is the lua script that makes use of this:
local test1 = Vector3.new(2, 3, 4);
local test2 = Vector3.new(1, 2, 3);
print(test1);
print(test2);
print(test1+2);
The last line produces an error, as it says I cannot add a userdata and a number together. However, in my vector class I tried to get it to just print what is being added, and just return the original data (to test). So I believe my problem is how I am defining my metatable; In my vector class, the two print's are never called.
print(test1+2); should be print(test1+test2);. You got that error because test1 is a userdata (basically an under-the-hood version of a table) and 2 is a number.
I have test case that does something like this
TestSquare.java
public void testEncaps() {
Shifting shift = new Shifting(150,260);
Square s = new Square(new Point(101,201),130,140,shift);
Point p = s.getMidPoint();
p.x = 215;
p.y = 315;
assertEquals(new Point(101,201),s.getMidPoint());
}
So on the last line, the s.getMidPoint() don't equal to the Point(101, 201) but instead gets overridden with 215,315. Here is my constructor code and get method.
Square.java
public Square(Point newP, int width, int height, Shift newS) {
this.newMidPoint = newP;
this.newWidth = width;
this.newHeight = height;
this.newShift= newS;
}
public Point getMidPoint() {
return newMidPoint;
}
So, s.getMidPoint() shouldn't be replaced with the Point object. What am I doing wrong?
This two codes are in different class. So there is no main method in Square.java
If you don't want another class to be able to edit Square's middle, return a new Point:
public Point getMidPoint() {
return new Point(newMidPoint);
}
Then your test will run green.
I have been instructed to "Write a class, Triangle, with one instance variable that takes two string values, (filled or not filled)".
I'm new to Java, and still haven't come across a situation where you could have two potential values for one instance variable.
How would I do this?
main method was given:
public static void main(String[] args)
{
TwoDPolygon polygons[] = new TwoDPolygon[3];
polygons[0] = new Triangle("filled", 8.5, 12.0);
polygons[1] = new Triangle("not Filled", 6.5, 7.5);
polygons[2] = new Triangle(7.0);
for (int i=0; i<polygons.length; i++)
{
System.out.println("Object is " + polygons[i].getName());
System.out.println("Triangle " + polygons[i].getStatus());
System.out.println("Area is " + polygons[i].area());
}
}
Ok I have redesigned the code based on your updated question.
First of all, you need an abstract class called TwoDPolygon. This class is an abstract representation of all your polygons. It contains the constructors and the methods you need.
abstract class TwoDPolygon {
protected String filled;
protected double x;
protected double y;
protected TwoDPolygon(String filled, double x, double y){
this.filled=filled;
this.x=x;
this.y=y;
}
protected TwoDPolygon(double x, double y){
this.x=x;
this.y=y;
}
protected TwoDPolygon(double y){
this.y=y;
}
abstract String getName();
abstract String getStatus();
abstract Double area();
}
Then the next step is to create the Triangle class. You will have to extend the abstract TwoDPolygon. This is the code:
public class Triangle extends TwoDPolygon {
//the first constructor
public Triangle(String filled, double x, double y) {
super(filled, x, y);
}
//the second one
public Triangle(double x, double y){
super(x,y);
}
//the third one
public Triangle(double y){
super(y);
}
public String getName() {
return "Triangle";
}
public String getStatus() {
return filled;
}
public Double area() {
//Insert code here which calculates the area
return 0.0;
}
}
This is all. Every time when you instantiate a Triangle polygon it will chose the right constructor based on the parameters you supply. Now when you run your main you will have the following output:
Object is Triangle
Triangle filled
Area is 0.0
Object is Triangle
Triangle not Filled
Area is 0.0
Object is Triangle
Triangle null
Area is 0.0
Note: The area's code is not done. You will have to do that but I guess that shouldn't be a problem.
Also I have created three constructors as you said, but I don't know the parameters of the third one. I just guessed that it has only the x and y value.
I hope this is what you're looking for!! It shouldn't be that hard to adapt to your specific requirements, as I think it looks almost done.
It is most likely meant that it takes one argument with 2 valid values:
class Triangle {
Triangle(String val) {
if (!"filled".equals(val) || !"not filled".equals(val))
throw ...;
}
}
or enum type
public enum Type {
FILLED,
NOT)FILLED
}
I think what is meant is you have one boolean instance variable named isFilled.
then you could have something like this:
boolean isFilled;
public triangle(String filled, int x, int y) {
if (filled == "filled") {
isFilled = true;
} else if (filled == "notFilled") {
isFilled = false;
} else {
//handle exception or whatever
}
}
That way you can have one instance variable but still use a string in the constructor. I don't think this is a very practical thing to do but if that is what your assignment said then that is a good way to do it. I hope I helped!
I have been trying without any luck to make a list of all points in a model. When i execute this
HashList<Point> points=new HashList<Point>(16);
//add +y side
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(-5.0,5.0,5.0));
points.add(new Point(5.0,5.0,5.0));
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(5.0,5.0,5.0));
points.add(new Point(5.0,5.0,-5.0));
//add -x side
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(-5.0,-5.0,-5.0));
points.add(new Point(-5.0,-5.0,5.0));
points.add(new Point(-5.0,5.0,-5.0));
points.add(new Point(-5.0,-5.0,5.0));
points.add(new Point(-5.0,5.0,5.0));
int length=points.length(); //equals 12, 6 expected
Point a=new Point(-5.0,5.0,-5.0);
Point b=new Point(-5.0,5.0,-5.0);
int aHashCode=a.hashCode(); //-737148544
int bHashCode=b.hashCode(); //-737148544
boolean equals=a.equals(b); //true
points containts 12 points which is the number I started with. I want all duplicates found which should result in only 6 points in table.
if (map.containsKey(e)) {
in HashList for some reason never gets executed. Any ideas?
HashList:
package dataTypes;
import java.util.ArrayList;
import java.util.HashMap;
public class HashList<E> {
private HashMap<E,Integer> map;
private ArrayList<E> data;
private int count=0;
public HashList() {
map=new HashMap<E,Integer>();
data=new ArrayList<E>();
}
public HashList(int size) {
map=new HashMap<E,Integer>(size);
data=new ArrayList<E>(size);
}
public int add(E e) { //returns key
if (map.containsKey(e)) {
return map.get(e);
} else {
map.put(e, count);
data.add(count,e);
return count++;
}
}
public int getKey(E e) {
return map.get(e);
}
public E get(int key) {
return data.get(key);
}
public int length() {
return count;
}
}
Point:
package geometry3D;
/**
* 3D point location or vector
*
* #author Matthew Cornelisse
* #version 2014-09-02-004500
*/
public class Point
{
// instance variables - replace the example below with your own
public double x;
public double y;
public double z;
/**
* Constructor for objects of class Point
*/
public Point()
{
// initialise instance variables
x = 0;
y = 0;
z = 0;
}
public Point(double x, double y, double z)
{
this.x=x;
this.y=y;
this.z=z;
}
public Point(Point a) {
x=a.x;
y=a.y;
z=a.z;
}
/**
* Normailizes the point to have distance from center of 1
*
*/
public void normalize()
{
// put your code here
double length=Math.sqrt(x*x+y*y+z*z);
x/=length;
y/=length;
z/=length;
}
//implements Shape
public void rotateX(double angle){
double newY=Math.cos(angle)*y-Math.sin(angle)*z;
double newZ=Math.sin(angle)*y+Math.cos(angle)*z;
y=newY;
z=newZ;
}
public void rotateY(double angle){
double newX=Math.cos(angle)*x-Math.sin(angle)*z;
double newZ=Math.sin(angle)*x+Math.cos(angle)*z;
x=newX;
z=newZ;
}
public void rotateZ(double angle){
double newX=Math.cos(angle)*x-Math.sin(angle)*y;
double newY=Math.sin(angle)*x+Math.cos(angle)*y;
x=newX;
y=newY;
}
public void rotate(Vector axis, double angle){
//source: http://inside.mines.edu/fs_home/gmurray/ArbitraryAxisRotation/
double oldX=x;
double oldY=y;
double oldZ=z;
double sinA=Math.sin(angle);
double cosA=Math.cos(angle);
Point offset=axis.offset();
Point vector=axis.vector();
double u=vector.x;
double v=vector.y;
double w=vector.z;
double a=offset.x;
double b=offset.y;
double c=offset.z;
x=(a*(v*v+w*w)-u*(b*v+c*w-u*oldX-v*oldY-w*oldZ))*(1-cosA)+oldX*cosA+(-c*v+b*w-w*oldY+v*oldZ)*sinA;
y=(b*(u*u+w*w)-v*(a*u+c*w-u*oldX-v*oldY-w*oldZ))*(1-cosA)+oldY*cosA+(c*u-a*w+w*oldX-u*oldZ)*sinA;
z=(c*(u*u+v*v)-w*(a*u+b*v-u*oldX-v*oldY-w*oldZ))*(1-cosA)+oldZ*cosA+(-b*u+a*v-v*oldX+u*oldY)*sinA;
}
public void move(double x, double y, double z){
this.x+=x;
this.y+=y;
this.z+=z;
}
public void move(Vector direction,double magnitude){
this.x+=(direction.vector().x*magnitude);
this.y+=(direction.vector().y*magnitude);
this.z+=(direction.vector().z*magnitude);
}
public boolean equals(Point compare) {
if (Math.abs(compare.x-x)>5*Math.ulp(compare.x)) return false;
if (Math.abs(compare.y-y)>5*Math.ulp(compare.y)) return false;
if (Math.abs(compare.z-z)>5*Math.ulp(compare.z)) return false;
return true;
}
public boolean equals(Point compare, double error) {
if (Math.abs(compare.x-x)>error) return false;
if (Math.abs(compare.y-y)>error) return false;
if (Math.abs(compare.z-z)>error) return false;
return true;
}
public int hashCode(){
Double a=(Double)x;
Double b=(Double)y;
Double c=(Double)z;
return a.hashCode()^Integer.rotateRight(b.hashCode(),12)^Integer.rotateRight(c.hashCode(),24);
}
public boolean equals(Object compare) {
try {
Point temp=(Point)compare;
if (temp.x!=x) return false;
if (temp.y!=y) return false;
if (temp.z!=z) return false;
return true;
} finally {
return false;
}
}
}
As noticed by rolfl, it is no use to try to use java equals method to compare Points with an acceptable error (see TL/DR section below if you are in doubt).
So, you have to do it the hard way. Do not even imagine to use map.containsKey(e), but create an explicit method in HashList. I would begin by that interface :
public interface DistEquality<E> {
boolean distEquals(E compare);
}
Then declare Point to implement it :
public class Point implements DistEquality<Point> {
...
public static double defaultError = 10E-3;
#Override
public boolean distEquals(Point compare) {
return equals(compare, defaultError);
}
}
And modify HashList that way
public class HashList<E extends DistEquality<E>> {
...
public int distValue(E e) {
for (Entry<E, Integer> entry: map.entrySet()) {
if (e.distEquals(entry.getKey())) {
return entry.getValue();
}
}
return -1;
}
public int add(E e) { //returns key
int pos = distValue(e);
if (pos != -1) {
return pos;
} else {
map.put(e, count);
data.add(count,e);
return count++;
}
}
...
}
I have not tested anything, but I think the general idea should be Ok.
TL/DR
Below solution is plain wrong - (thanks to rolfl to noticing)
The equals method in class Point requires exact equality of doubles. You should instead have a static double defaultError in Point class, initialized at an appropriate value and then do :
public boolean equals(Object compare) {
return ((compare instanceof Point) ? equals(compare, defaultError) : false);
}
But as noticed by rolfl, this is not enough, because javadoc for Object.hashCode() states If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It would be very hard to imagine an intelligent hash compatible with the above equality method. Worse, once one point gets a hashCode value, any other point is at a finite number of defaultError and you can imagine a finished suite of Points that are all 2 per 2 equals and so hashCode should be a constant.
Worse, as equals is required to be reflexive, symetric and transitive, all Points should be equal.
It looks that the idea of using equal that way is really a bad idea :-(
The problem is your finally block in equals(Object). It's always returning false, even if you're returning true from the try block.
You're getting confused because of this:
boolean equals=a.equals(b); //true
... but that's not calling the same equals method - it's calling equals(Point).
Your equals(Object) method should be written as:
#Override public boolean equals(Object compare) {
if (compare == this) {
return true;
}
if (compare == null || compare.getClass() != getClass()) {
return false;
}
Point temp = (Point) compare; // Guaranteed to work now
return temp.x == x && temp.y == y && temp.z == z;
}
Note that:
As noted elsewhere, you can't come up with an equality/hash which handles tolerance... if you do any significant arithmetic with these points, you're unlikely to have exact equality any more
Your class has public fields, which is pretty much always a bad idea
Your class is mutable, which is a bad idea from the point of view of code using the hash code - collections are much easier to use correctly when the element type is immutable
If you make your class final, you can use instanceof instead of the getClass() check - and again, that would help prevent someone introducing a mutable subclass. (Equality relationships across an inheritance hierarchy are generally painful anyway.)
The HashList implementation is incorrect if you want it to be able to contain duplicates. On your add, if the map already has the key, you just return the value..., so your duplicates will never get inserted.
If you are getting duplicates, that means that your Equals/HashCode for Point is likely screwed up.
Right now, your HashList doesnt actually allow duplicates, so you might as well just get rid of it and use a HashSet from java collections. Also, get a decent java IDE like netbeans, eclipse, IntellIJ and have it generate the equals/hashcode for you on your point class.