public class RightAngleTriangle
{
int height;
int width;
double area;
double perimeter;
public RightAngleTriangle()
{
height = 1;
width = 1;
}
public RightAngleTriangle(int hei, int wid)
{
if(hei > 0 && wid > 0)
{
height = hei;
width = wid;
}
else
{
height = 1;
width = 1;
}
}
public double area()
{
area = height * width;
return area;
}
public double perimeter()
{
perimeter = (height * 2) + (width * 2);
return perimeter;
}
public boolean isIsosceles()
{
if(height == width)
{
return true;
}
return false;
}
public boolean largerThan(RightAngleTriangle anotherRightAngleTriangle)
{
if (area(RightAngleTriangle) > area(anotherRightAngleTriangle))
{
}
}
}
For the method largerThan() how can I make it so largerThan() returns true if and only if the area of this RightAngleTriangle is larger than the area of anotherRightAngleTriangle. I am not sure how to compare the areas because the area is calculated locally. I tried initializing area globally but I need the returned value not the initialized value.
Just as a comment largerThan() is not a constructor, is a method
now to your question
you need to call the method in the current instance and in the object passed as parameter
public boolean largerThan(RightAngleTriangle anotherRightAngleTriangle)
{
if (this.area() > anotherRightAngleTriangle.area( ))
{
//your logic
}
}
or simple doing
public boolean largerThan(RightAngleTriangle anotherRightAngleTriangle)
{
return this.area() > anotherRightAngleTriangle.area();
}
Related
So i code consist of 3 parts 2 classes and test.
This is code for 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())
);
}
Class Point works fine, and i am ading it just for clarity
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;
}
}
This is class for Rectangle itself, and it includes both constructor and aditional methods.
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(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;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
Main problem is that this code return only zeroes in tests, i guess problem is in rectangle class in constructor, or aditionalmethods.
Your constructor for Rectangle is always setting width and height to 0. I think the constructor should look something like...
public Rectangle(Point center, int width, int height) {
int x = 0;
int y = 0;
this.width=width;
this.height=height;
this.center=center;
}
Say I have this view with two subviews A and B, A and B has a color property mColor,
I want a function in the parent view that has this signature: int getColor(int x, int y), which for any given x and y coordinate, return the color at that position, if the x and y coordinates land and the two shapes are overlapped, return the average color of A and B
The problem I am running into is i see myself doing a lot of conditional checks, checking if A is left of B or if A is right of B etc. I feel like I am missing some key intuition
I have a Point class that handles the coordinates"
public class Point {
private final int mX;
private final int mY;
public Point(int mX, int mY) {
this.mX = mX;
this.mY = mY;
}
public int getX() {
return mX;
}
public int getY() {
return mY;
}
}
Here is my subview class:
public class Chart {
private int mColor;
private Point mTopLeft;
private Point mBottomRight;
public Point getTopLeft() {
return mTopLeft;
}
public Point getBottomRight() {
return mBottomRight;
}
public Chart(int mColor, Point topLeft, Point bottomRight) {
this.mColor = mColor;
this.mTopLeft = topLeft;
this.mBottomRight = bottomRight;
}
public int getColor() {
return mColor;
}
public Point getTopRightCorner() {
return new Point(getBottomRight().getX(), getTopLeft().getY());
}
public Point getBottomLeftCorner() {
return new Point(getTopLeft().getX(), getBottomRight().getY());
}
}
My parent view class:
public class View {
private Chart mChartA;
private Chart mChartB;
public View(Chart chartA,
Chart chartB) {
mChartA = chartA;
mChartB = chartB;
}
public boolean doChartsOverlap() {
boolean isOverlapped = true;
if(isChartALeftOfChartBInX() || isChartARightOfChartBInX()) {
isOverlapped = false;
}
if(isChartABottomOfChartBInY() || isChartATopOfChartBInY()) {
isOverlapped = false;
}
return isOverlapped;
}
public final boolean isChartALeftOfChartBInX() {
return mChartA.getBottomRight().getX() <= mChartB.getTopLeft().getX();
}
public final boolean isChartARightOfChartBInX() {
return mChartA.getTopLeft().getX() >= mChartB.getBottomRight().getX();
}
public final boolean isChartATopOfChartBInY() {
return mChartA.getBottomRight().getY() <= mChartB.getTopLeft().getY();
}
public final boolean isChartABottomOfChartBInY() {
return mChartA.getTopLeft().getY() >= mChartB.getBottomRight().getY();
}
public void setChartA(Chart mChartA) {
this.mChartA = mChartA;
}
public void setChartB(Chart mChartB) {
this.mChartB = mChartB;
}
}
Logically, you want to test if the point is in both rectangles; so test if it is in one rectangle and also in the other rectangle. Everything else about whether one rectangle is above, below, left or right of the other is a red herring.
Add this method to the Chart class (use < instead of <= if you only want to paint the interiors):
public boolean contains(Point p) {
return mTopLeft.getX() <= p.getX() && p.getX() <= mBottomRight.getX()
&& mTopLeft.getY() <= p.getY() && p.getY() <= mBottomRight.getY();
}
And this method to the View class:
public int getColor(Point p) {
boolean inA = mChartA.contains(p), inB = mChartB.contains(p);
if(inA && inB) {
// ...
} else if(inA) {
// ...
} else if(inB) {
// ...
} else {
// ...
}
}
You can then overload public int getColor(int x, int y) to return getColor(new Point(x, y)).
Rectangle r1 = new Rectangle(x1, y1, width1, height1 );
Rectangle r2 = new Rectangle(x2, y2, width2, height2);
if ( r1.contains( x3, y3 ) && r2.contains( x3, y3 ) ) {
// (x3,y3) is in both rectangles
}
Create a class Rectangle with instance variables length and width to
have default value of 1 for both of them. The class should have
suitable set and get methods for accessing its instance variables. The
set methods should verify that length and width are assigned a
value that is larger than 0.0 and is lesser than 20.0, Provide
suitable public methods to calculate the rectangle’s perimeter and
area. Write a suitable class "RectangleTest" to test the Rectangle
class.
What I came up with:
package rectangle;
public class Rectangle
{
private double width;
private double length;
public Rectangle()
{
width=1;
length=1;
}
public Rectangle(double width, double length)
{
this.width = width;
this.length = length;
}
public void setWidth(float width)
{
this.width = width;
}
public float getWidth()
{
return (float) width;
}
public void setLength(float length)
{
this.length = length;
}
public float getLength()
{
return (float) length;
}
public double getPerimeter()
{
return 2 * (width + length);
}
public double getArea()
{
return width * length;
}
}
package rectangle;
import java.util.Scanner;
public class RectangleTest extends Rectangle
{
public static void main(String[] args)
{
Scanner RectangleTest = new Scanner(System.in);
System.out.print("Length: ");
float lengthInput = RectangleTest.nextFloat();
System.out.print("Width: ");
float widthInput = RectangleTest.nextFloat();
Rectangle rectangle = new Rectangle (lengthInput, widthInput);
System.out.printf("Perimeter: %f%n",
rectangle.getPerimeter());
System.out.printf("Area: %f%n",
rectangle.getArea());
}
}
Code is fine, it's just I am not sure how to implement the between 0 - 20 without breaking everything and have tried different things.
I'd check it and throw an IllegalArgumentException if the value isn't valid, e.g.:
public void setLength(float length) {
if (length <= 0f || length >= 20.0f) {
throw new IllegalArgumentException("Invalid length " + length);
}
this.length = length;
}
i wan't to create effect similar to that of photoshop when you press ctrl+T that produces frame around the object and resize but i want to just change the position of the contained object not scaling them what i created so far does the job but the movement is exagerrated and i can't figure out what is wrong with my codehere i am just trying with the northwest handler
thanks in advance
here is images illustrating exactly what i want
the first image is original group with blue circles are controllers
the second is the group after resizing the group by dragging the north west
but the components gets scaled also
the third one is exactly what i want to achieve only change positions without changing the scale
//this creates the bounding box
public static void cr_resizer(Group root,double x,double y,double X,double Y) {
Rectangle major=new Rectangle(x-10,y-10,X-x+20,Y-y+20);
major.setFill(Color.TRANSPARENT);
major.setId("major");
major.setStrokeWidth(3);
major.setStroke(Color.BLUE);
major.setDisable(true);
Circle NW=new Circle(x-10,y-10,3);
Circle N=new Circle(((x+X)/2),y-10,3);
Circle NE=new Circle(X+10,y-10,3);
Circle W=new Circle(x-10,(Y+y)/2,3);
Circle E=new Circle(X+10,(Y+y)/2,3);
Circle SE=new Circle(X+10,Y+10,3);
Circle S=new Circle(((x+X)/2),Y+10,3);
Circle SW=new Circle(x-10,Y+10,3);
resize_move( root,NW,SE);
root.getChildren().addAll(major,NW,N,NE,SE,S,SW,E,W);
}
//this function calculates the calculate the distance of the mover point from the opposing point
// to caclulate the scaling factor theen apply it to componnents of the group
public static void resize_move(Group root,Circle mover,Circle op) {
double[]start={mover.getCenterX(),mover.getCenterY()};
double[]end={op.getCenterX(),op.getCenterY()};
double[]strt_length=dis2_vec_d(start, end);
mover.setOnMouseClicked(ev->{
difx=ev.getX();
dify=ev.getY();
});
mover.setOnMouseDragged(ev->{
double diffx=ev.getX()-difx;
double diffy=ev.getY()-dify;
System.out.println(diffx);
System.out.println(diffy);
difx=ev.getX();
dify=ev.getY();
mover.setCenterX(ev.getX());
mover.setCenterY(ev.getY());
double[] newp= {mover.getCenterX(),mover.getCenterY()};
double[]end_length=dis2_vec_d(newp, end);
double[]factor = {end_length[0]/strt_length[0],end_length[1]/strt_length[1]};
for (Node nod:root.getChildren()) {
if (nod instanceof Circle) {
if (nod != mover) {
move_circ((Circle) nod,op,factor);
}
}
}
});
}
//this function relocate the position of the circle according to the position of the custom axis point
public static void move_circ(Circle cir,Circle op,double[]factor) {
double[] axis= {op.getCenterX(),op.getCenterY()};
double[] strt_point= {cir.getCenterX(),cir.getCenterY()};
double[] nstrt_point= new_cord(axis,strt_point,factor);
cir.setCenterX(nstrt_point[0]);
cir.setCenterY(nstrt_point[1]);
}
//this function scale the position of the point in relation to another point
public static double[] new_cord(double[]axis,double[]point,double[]factor) {
double[]strt_length=dis2_vec_d(point,axis);
double[]new_length= {strt_length[0]*factor[0],strt_length[1]*factor[1]};
double[]new_point= {new_length[0]+axis[0],new_length[1]+axis[1]};
return new_point;
}
//this function calculates the distance
public static double[] dis2_vec_d(double[]p1,double[]p2) {
double[] vec = new double[2];
vec[0]=p1[0]-p2[0];
vec[1]=p1[1]-p2[1];
return vec;
}
It looks like you just want to make your Node draggable. I created a class that does this, pasted below.
You might have to replace a few instances of a class called GameScreen in my code below.
public class Draggable {
////////////////////////////////////////////////////////////////////////////
//variables
AtomicBoolean myPressed = new AtomicBoolean(false);
Point2D myInitialTranslates;
Point2D dragInitialTranslates;
EventHandler<? super MouseEvent> onMouseReleased;
EventHandler<? super MouseEvent> onMousePressed;
EventHandler<? super MouseEvent> onMouseDragged;
OnDrag onDrag;
boolean stayWithinBounds = true;
double minX = 0;
double maxX = WIDTH;
double minY = 0;
double maxY = GameScreen.PLAY_AREA_HEIGHT;
boolean doNotTranslate = false;
//handleX and handleY are offsets used strictly for the callbacks, they are not used for the translation of the destination Node.
double handleX = 0;
double handleY = 0;
double X;
double Y;
boolean reverseX = false;
boolean reverseY = false;
float amountOfTargetNodeToAllowOutsideLimit = 0f;
public void setOnDrag(OnDrag onDrag) {
this.onDrag = onDrag;
}
////////////////////////////////////////////////////////////////////////////
//constructors
public Draggable() {
}
public Draggable(double handleX, double handleY) {
this.handleX = handleX;
this.handleY = handleY;
}
////////////////////////////////////////////////////////////////////////////
//methods
public void makeDraggable(Node source, Node target, double dragAdjustmentRatioX, double dragAdjustmentRatioY) {
source.setOnMouseDragged((MouseEvent event) -> {
if (myPressed.get() && !doNotTranslate) {
double x = myInitialTranslates.getX() - dragInitialTranslates.getX() + dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX());
double y = myInitialTranslates.getY() - dragInitialTranslates.getY() + dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY());
double localMaxX = maxX - target.getBoundsInLocal().getWidth() * amountOfTargetNodeToAllowOutsideLimit;
double localMinX = minX - target.getBoundsInLocal().getWidth() * amountOfTargetNodeToAllowOutsideLimit;
if (x > localMinX && x < localMaxX) {
target.setTranslateX(x);
} else {
// Log.debug("X is not within range. x = " + x);
}
double localMaxY = maxY - target.getBoundsInLocal().getHeight() * amountOfTargetNodeToAllowOutsideLimit;
double localMinY = minY - target.getBoundsInLocal().getWidth() * amountOfTargetNodeToAllowOutsideLimit;
if (y > localMinY && y < localMaxY) {
target.setTranslateY(y);
} else {
// Log.debug("Y is not within range. x = " + y);
}
} else {
}
if (onMouseDragged != null) {
onMouseDragged.handle(event);
}
if (onDrag != null) {
if (reverseX) {
X = handleX + dragInitialTranslates.getX() - dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX());
} else {
X = handleX - dragInitialTranslates.getX() + dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX());
}
if (reverseY) {
Y = handleY + dragInitialTranslates.getY() - dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY());
} else {
Y = handleY - dragInitialTranslates.getY() + dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY());
}
onDrag.handle(X, Y);
}
});
source.setOnMousePressed((MouseEvent event) -> {
myInitialTranslates = new Point2D(target.getTranslateX(), target.getTranslateY());
dragInitialTranslates = new Point2D(
dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX()),
dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY()));
myPressed.set(true);
if (onMousePressed != null) {
onMousePressed.handle(event);
}
GameScreen.setCursorMove();
});
source.setOnMouseReleased((MouseEvent event) -> {
myPressed.set(false);
handleX = X;
handleY = Y;
if (onMouseReleased != null) {
onMouseReleased.handle(event);
}
GameScreen.setCursorCustom();
});
}
public void makeDraggable(Node node, double dragAdjustmentRatioX, double dragAdjustmentRatioY) {
makeDraggable(node, node, dragAdjustmentRatioX, dragAdjustmentRatioY);
}
public void setOnMouseReleased(EventHandler<? super MouseEvent> onMouseReleased) {
this.onMouseReleased = onMouseReleased;
}
public void setOnMousePressed(EventHandler<? super MouseEvent> onMousePressed) {
this.onMousePressed = onMousePressed;
}
public void setOnMouseDragged(EventHandler<? super MouseEvent> onMouseDragged) {
this.onMouseDragged = onMouseDragged;
}
public void setAmountOfTargetNodeToAllowOutsideLimit(float amountOfTargetNodeToAllowOutsideLimit) {
this.amountOfTargetNodeToAllowOutsideLimit = amountOfTargetNodeToAllowOutsideLimit;
}
public interface OnDrag {
public void handle(double x, double y);
}
public boolean isStayWithinBounds() {
return stayWithinBounds;
}
public void setStayWithinBounds(boolean stayWithinBounds) {
this.stayWithinBounds = stayWithinBounds;
}
public void setMinMax(double minX, double maxX, double minY, double maxY) {
this.maxX = maxX;
this.minX = minX;
this.minY = minY;
this.maxY = maxY;
}
public void setDoNotTranslate(boolean doNotTranslate) {
this.doNotTranslate = doNotTranslate;
}
public boolean isReverseX() {
return reverseX;
}
public void setReverseX(boolean reverseX) {
this.reverseX = reverseX;
}
public boolean isReverseY() {
return reverseY;
}
public void setReverseY(boolean reverseY) {
this.reverseY = reverseY;
}
public double getHandleX() {
return handleX;
}
public void setHandleX(double handleX) {
this.handleX = handleX;
}
public double getHandleY() {
return handleY;
}
public void setHandleY(double handleY) {
this.handleY = handleY;
}
}
GameScreen.instance.scaleXToScreen and GameScreen.instance.scaleYToScreen just set this to 1. In the future if you scale your window, you might need to adjust for it.
GameScreen.WIDTH and GameScreen.PLAY_HEIGHT set tot he width and height of your scene.
The two method calls to change the mouse cursor can be deleted.
The way you use it is like this...
new Draggable().makeDraggable(nodeYouWantToDrag, 1, 1);
and thats that.
EDIT: it also has callbacks for basic events like onDrag, onMousePressed, onMouseDragged, and onMouseReleased.
I am creating an android app and I am creating a game and the droid has to be able to bounce off the walls and the edge of the screen. Here is my update method in my MainGamePanel.java file where I call the collision detection.
It works when it just has to bounce off the edge of the screen. However when I try to get it bounce off the wall objects it sometimes works. When it doesn't, it goes through the wall sometimes, although this only happens when it moves up and down. It also sometimes gets stuck in the wall. How would I modify the collision detection so I won't have these issues. Any help would be much appreciated.
public void update()
{
// check collision with right wall if heading right
if (droid.getSpeed().getxDirection() == Speed.DIRECTION_RIGHT
&& droid.getX() + droid.getBitmap().getWidth() / 2 >= getWidth()) {
droid.getSpeed().toggleXDirection();
}
// check collision with left wall if heading left
else if (droid.getSpeed().getxDirection() == Speed.DIRECTION_LEFT
&& droid.getX() - droid.getBitmap().getWidth() / 2 <= 0) {
droid.getSpeed().toggleXDirection();
droid.getSpeed().setYv(0);
}
// check collision with bottom wall if heading down
else if (droid.getSpeed().getyDirection() == Speed.DIRECTION_DOWN
&& droid.getY() + droid.getBitmap().getHeight() / 2 >= getHeight()) {
droid.getSpeed().toggleYDirection();
droid.getSpeed().setXv(0);
}
// check collision with top wall if heading up
else if (droid.getSpeed().getyDirection() == Speed.DIRECTION_UP
&& droid.getY() - droid.getBitmap().getHeight() / 2 <= 0) {
droid.getSpeed().toggleYDirection();
droid.getSpeed().setXv(0);
}
for (int i = 0 ; i < listOfWs.length ; i++)
{
if (droid.getX() +(droid.getBitmap().getWidth()/2)+1 > listOfWs [i].giveLeft ()
&& droid.getX()-(droid.getBitmap().getWidth()/2)-1 < listOfWs [i].giveRight ()
&& droid.getY()+(droid.getBitmap().getHeight()/2)+1 > listOfWs [i].giveTop ()
&& droid.getY()-(droid.getBitmap().getHeight()/2)-1 < listOfWs [i].giveBottom () )
{
if(droid.getSpeed().getYv()==0){
droid.getSpeed().toggleXDirection();//Takes the speed and multiplies it by -1 so it changes direction
}
else{
droid.getSpeed().toggleYDirection();
}
}
}
// Update the lone droid
droid.update();
}
Here is my droid.java file that I used.
public class Droid {
private Bitmap bitmap; // the actual bitmap
private int x; // the X coordinate
private int y; // the Y coordinate
public Speed speed;
public Droid(Bitmap bitmap, int x, int y) {
this.bitmap = bitmap;
this.x = x;
this.y = y;
speed= new Speed();
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
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 draw(Canvas canvas) {
canvas.drawBitmap(bitmap, x - (bitmap.getWidth() /2), y - (bitmap.getHeight() / 2), null);
}
public void update() {
x += (int)(speed.getXv() * speed.getxDirection());
y += (int)(speed.getYv() * speed.getyDirection());
}
public Speed getSpeed(){
return speed;
}
}
This is the speed.java file.
public class Speed {
public static final int DIRECTION_RIGHT = 4;
public static final int DIRECTION_LEFT = -4;
public static final int DIRECTION_UP = -4;
public static final int DIRECTION_DOWN = 4;
private float xv = 1; // velocity value on the X axis
private float yv = 1; // velocity value on the Y axis
private int xDirection = DIRECTION_RIGHT;
private int yDirection = DIRECTION_DOWN;
public Speed() {
this.xv = 1;
this.yv = 1;
}
public Speed(float xv, float yv) {
this.xv = xv;
this.yv = yv;
}
public float getXv() {
return xv;
}
public void setXv(float xv) {
this.xv = xv;
}
public float getYv() {
return yv;
}
public void setYv(float yv) {
this.yv = yv;
}
public int getxDirection() {
return xDirection;
}
public void setxDirection(int xDirection) {
this.xDirection = xDirection;
}
public void setRight() {
xDirection = DIRECTION_RIGHT;
}
public void setLeft() {
xDirection = DIRECTION_LEFT;
}
public void setUp() {
yDirection = DIRECTION_UP;
}
public void setDown() {
yDirection = DIRECTION_DOWN;
}
public int getyDirection() {
return yDirection;
}
public void setyDirection(int yDirection) {
this.yDirection = yDirection;
}
// changes the direction on the X axis
public void toggleXDirection() {
xDirection = xDirection * -1;
}
// changes the direction on the Y axis
public void toggleYDirection() {
yDirection = yDirection * -1;
}
}
in the update method, in for circulation, it seems you make your logical operation there, would you make it more specific?