I'm writing a Rectangle class and it has 2 instance variables which are 2 points that are called _pointSW and _pointNE. I have to define the width and the height of the rectangle, but I can't use any other variables besides the 2 points.
I want to ask how I could write the getWidth() method, for example using just the _pointNE, or maybe better write a private method (because I can't use any new public methods) to define the width and the height, and then use it in other methods and if that's an option, then how do I actually write it? thanks!
If your SW means South-West and NE means North-East:
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
}
public class Rectangle {
private Tuple<double,double> pointSW;
private Tuple<double,double> pointNE;
public Rectangle(final Tuple<double,double> sw, final Tuple<double,double> ne) {
this.pointSW = sw;
this.pointNE = ne;
}
public double getWidth() {
return Math.abs(this.pointNE.x - this.pointSW.x);
}
public double getHeight() {
return Math.abs(this.pointSW.y - this.pointNE.y);
}
public void setWidth(final double width) {
this.pointNE.x = this.point.SW.x + width;
}
public void setHeight(final double eight) {
this.pointNE.y = this.point.SW.y + eight;
}
}
Related
I tried to declare two variable x and y, then create constructor for them and getters with setters. So, for this I used class Distance, while for the obtaining shape I need another class.
package com.company;
import java.lang.Math;
public class Point {
//fields
private int x;
private int y;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
//method
//getters
public int getX() {
return x;
}
public int getY() {
return y;
}
//setters
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getPoint(){
}
//function distance
public void distance() {
//**here I need somehow use only two variables instead of four**
double res = Math.sqrt((Math.pow(getX1(), 2) - Math.pow(getX2(), 2))
+ (Math.pow(getY1(), 2) - Math.pow(getY2(), 2)));
System.out.println(res);
}
}
Create a function that accepts object of type Point. The function returns the distance between the original point and passed point
public void distance(Point po) {
//**here I need somehow use only two variables instead of four**
double res = Math.sqrt(
Math.pow(getX() - po.getX(), 2) +
Math.pow(getY() - po.getY(), 2)
);
System.out.println(res);
}
Also your function to calculate distance was wrong.
This is using Processing 3.5, not every java thing works the same here.
The Bird class is giving me the error saying it needs to implement call(). Isn't it already under the main? I'm not experienced with interfaces so I don't know what exactly is going on here.
public interface FuncCall<A> {
A call();
}
class Bird implements FuncCall{
//Error here ^
//The type FuncCallTest.Bird must implement the inherited abstract method FuncCallTest.FuncCall.call()
//Is this not implemented already under main?
float x, y, size;
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Bird(float x, float y, float size){
this.x = x;
this.y = y;
this.size = size;
}
public void main(String[] args){
FuncCall<Float> getX = new FuncCall<Float>(){
#Override
public Float call(){
return x;
}
};
FuncCall<Float> getY = new FuncCall<Float>(){
#Override
public Float call(){
return y;
}
};
FuncCall<Float> getSize = new FuncCall<Float>(){
#Override
public Float call(){
return size;
}
};
inputs.add(getX);
inputs.add(getY);
inputs.add(getSize);
}
}
class Pol {
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Pol(ArrayList<FuncCall<Float>> inputs){
this.inputs = inputs;
}
//public float call(ArrayList<FuncCall<Float>> arr, int index){
//return arr.get(index).call();
//}
//How do I do this? Do I need to implement the interface here as well? Because if so same error as on Bird
}
I'll also stick this extra bit on the end here.
System.out.println(pol.call(pol.inputs, 1));
Does will that work? It doesn't error before compiling.
I appreciate any help. Please ask if something doesn't make sense as I'm still new to stack and not the best with java. :)
main file :
void setup(){
Bird bird = new Bird(1.2, 3.2, 7.5);
Pol pol = new Pol(bird.inputs);
System.out.println(pol.call(pol.inputs, 1););
}
First of all you could skip your FuncCall interface and use Java's Supplier functional interface and just add these Suppliers respectively method references of your class objects getters to the list.
Another approach is to provide an interface or abstract class that has getters and/or member variables for x, y and size and use this interface or abstract class as type parameter for the list.
With Suppliers:
This is closer to your example and requires less changes in
your code.
The second option with an interface changes your Pol class
completely and I am not sure if this is acceptable for you.
´
public class Bird {
private float x;
private float y;
private float size;
public Bird(float x, float y, float size) {
//set your members here
}
public Float getX() {
return this.x;
}
public Float getY() {
return this.y;
}
public Float getSize() {
return this.size;
}
}
´
Then the Pol class
´
public class Pol {
private final List<Supplier<Float>> inputs;
public Pol(List<Supplier<Float>> inputs) {
this.inputs = inputs;
}
public Float call(int index) {
return this.inputs.get(index).get();
}
}
´
And your main should look like
´
public static int main(String[] args) {
Bird bird = new Bird(1.0f, 1.0f, 2.5f);
Pol pol = new Pol(Arrays.asList(bird::getX,
bird::getY, bird::getSize));
Float birdsSize = pol.call(2);
return 0;
}
´
The Cube class have two constructors, one which accepts three parameters that are converted into the tree attributes of the cube, and another one that doesn't require any parameter and therefore creates an "empty" cube. My question is how can a boolean method check if the cubes are valid or empty? Is there a way to do that without the need of checking each one of the attributes?
class Application {
public static void main(String[] args) {
Cube c1 = new Cube(4, 3, 6);
Cube c2 = new Cube();
System.out.println(isNotEmpty(c1));
System.out.println(isNotEmpty(c2));
}
public static boolean isNotEmpty(Cube cube) {
if (/*cube attributes are NOT empty*/) {
return true;
} else {
return false;
}
}
public static class Cube {
private int height;
private int width;
private int depth;
public Cube() {}
public Cube(int height, int width, int depth) {
this.height = height;
this.width = width;
this.depth = depth;
}
public int getHeight() { return height; }
public int getWidth() { return width; }
public int getDepth() { return depth; }
}
}
Since it appears that the only state which a Cube has are the height, width, and depth, then you could actually just use null to represent an empty Cube.
It doesn't make much sense to call a cube with no dimensions a cube in the first place. Using null as a marker might make the most sense.
Either change one (or more) of your int fields to be an Integer Object, or introduce a new Boolean field isSet or get rid of your empty constructor
1) If you use an Integer Object you can test to see if it is null where -as int primitives have a default value of 0
2) If you have a Boolean field you can default it to false and set it to true in your proper constructor
Use a bool flag isEmptyCube in the constructor. At the time of object creation, it will be automatically marked correctly whether it is blank or not.
public static class Cube {
//...
private boolean isEmptyCube;
public Cube() {isEmptyCube = true;}
public Cube(int hight, int width, int depth) {
//...
isEmptyCube = false;
}
public isCubeEmpty() { return isEmptyCube;}
It seems a so tricky question. At first, we have to have any criteria: What is an empty object?. When we have some criteria, even single, we must check it.
From the reason when we are considering the Cube c3 = new Cube(0, 0, 0) like is not empty, so, here is one of ways:
public class CubeApplication {
public static void main(String[] args) {
Cube c1 = new Cube(4, 3, 6);
Cube c2 = new Cube();
Cube c3 = new Cube(0, 0, 0);
System.out.println(c1.isEmpty());
System.out.println(c2.isEmpty());
System.out.println(c3.isEmpty());
}
static class Cube {
private int hight;
private int width;
private int depth;
private boolean isEmpty;
public Cube() {
this.isEmpty = false;
}
public Cube(int hight, int width, int depth) {
this.hight = hight;
this.width = width;
this.depth = depth;
this.isEmpty = true;
}
public boolean isEmpty() {
return this.isEmpty;
}
public int getHight() {
return this.hight;
}
public int getWidth() {
return this.width;
}
public int getDepth() {
return this.depth;
}
}
}
OUTPUT:
true
false
true
I'm writing a game which contains elevators as an obstacle. An elevator spawns either left or right of the screen and has a random chance to be an ascending elevator or a descending elevator. It looks like this:
public class Elevator extends WorldObject {
public static boolean ascending;
public Elevator(int screenHeight, int xPos) {
super(xPos, screenHeight, 0, 0);
ascending = new Random().nextBoolean();
}
static public boolean isAscending(){
return ascending;
}
}
WorldObject from which it extends looks like this:
public class WorldObject {
protected float posX;
protected float posY;
protected float velX, velY;
public float getPosX() {
return posX;
}
public void setPosX(float posX) {
this.posX = posX;
}
public float getPosY() {
return posY;
}
public void setPosY(float posY) {
this.posY = posY;
}
public float getVelX() {
return velX;
}
public void setVelX(float velX) {
this.velX = velX;
}
public float getVelY() {
return velY;
}
public void setVelY(float velY) {
this.velY = velY;
}
public WorldObject(float posX, float posY, float velX, float velY) {
this.posX = posX;
this.posY = posY;
this.velX = velX;
this.velY = velY;
}
}
Every 5 seconds an elevator will be created and added to an ArrayList of Elevators like so:
if (timeToElevator > 5.0f) {
timeToElevator = 0;
Elevator elevator = new Elevator((int) screenHeight, (int) generateElevatorXPos());
Sprite eSprite = new Sprite(elevatorTexture);
eSprite.setOrigin(0, 0);
elevators.add(elevator);
elevatorSprites.add(eSprite);
}
I then check for collisions in each elevator with the player, remove it if it goes out of bounds and if neither of these happen I update the position of the elevator object:
public static void calculateElevatorCollisions() {
int counter = 0;
for (Iterator<Elevator> i = elevators.iterator(); i.hasNext(); ) {
Elevator item = i.next();
if (item.getPosY() < -100) {
//remove elevator
} else if (..collision..) {
//collision
} else {
item.setVelY(item.isAscending() ? -5 : 5);
item.setPosY(item.getVelY() + item.getPosY());
elevatorSprites.get(counter).setPosition(item.getPosX(),
item.getPosY());
counter++;
}
My issue is whenever a new Elevator is created all current Elevators change their direction to the direction of the new Elevator. So suppose I have two ascending elevators being drawn, whenever my third elevator is created to be descending, the other two previously ascending elevators now ascend!
What's causing this?
This is your problem:
public static boolean ascending;
^^^^^^
static means "This is a class field that is shared by all objects". So if you changed the field from one object, it will be noticed across all objects of that type.
Removing it to make ascending an instance field means that each instance of Elevator will have its own copy which it can modify by itself without changing other instances' copy.
Change
public static boolean ascending;
To
public boolean ascending;
When you set a variable as static it is a class variable, not an instance variable. Class variables are variables that are shared across all instances of an object, whereas instance variables are specific to that instance of the object.
As I can't comment yet (rep), I want to make another note:
You are practicing encapsulation using the getter for ascending, isAscending(); however, the field you are encapsulating is public, making it accessible from all scopes.
It's good practice to keep encapsulated fields private.
Also, it seems as if everyone is only stating that the field be changed to a non-static variable; however, the method is still static, even though it is actually an instance method as well!
Resulting changes needed:
public static boolean ascending;
becomes
private boolean ascending;
...and...
static public boolean isAscending()
becomes
public boolean isAscending()
This question already has answers here:
Why can I access my private variables of the "other" object directly, in my equals(Object o) method
(2 answers)
Closed 8 years ago.
and thanks everyone for fixing formats etc, totally new here
I recently started learning java and one question occurred to me during one exercise, sorry if i missed posting rules:
to calculate distance from one MyPoint to another Mypoint, I decided to use a getter for MyPoint another since x and y for another should be private and can't be used on dot operation (another.x another.y);
public class MyPoint {
private int x;
private int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(MyPoint another) {
int xDiff = this.x - another.getX(); //getter
int yDiff = this.y - another.getY(); // getter
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint a = new MyPoint(3,0);
MyPoint b = new MyPoint(0,4);
System.out.println(a.distance(b)); // this works fine;
}
}
however, if i go back to the code and change another.getX() to another.x, the code still works. and same for y.
public class MyPoint {
private int x;
private int y;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(MyPoint another) {
int xDiff = this.x - another.x; //no getter
int yDiff = this.y - another.y; //no getter
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint a = new MyPoint(3,0);
MyPoint b = new MyPoint(0,4);
System.out.println(a.distance(b)); // this still works fine;
}
}
i thought since another is a MyPoint class and instance x and y are private, there's no way for .x and .y to work, and that's the whole point of setting instance private and uses a getter.
what did i miss?
private means that the fields can only be accessed from within MyPoint. It doesn't mean that they can only be accessed from with the same instance of MyPoint. It's perfectly legitimate for methods that operate on "other" instances, especially equals and compareTo, to access private state in other instances of the same class.