For example, I have got a code like this:
class Point
{
private String x;
private String y;
public String getX () { //Here can not use Optional<String>
return this.x;
}
public String getY () {
return this.y;
}
public Point(String x, String y) {
this.x = x;
this.y = y;
}
}
...
Point point = new Point(null, "14.2");
if(ofNullable(point.getX().isPresent()) {
this.xCoordinate = point.getX();
}
if(ofNullable(point.getY().isPresent()) {
this.yCoordinate = point.getY();
}
I want to do it in a cleaner way, something like this:
this.x = ofNullable(point.getX()).ifPresent((x) -> x)
I know this is not working but I tried almost everything but I can not get it to work.
You have to use Integer instead of the primitive type int
You didn't post enough code, but your getX method definition should be:
Optional<Integer> getX() instead of int getX().
If you can't modify the class with the method, create a wrapper class or something. Without seeing all the code, I can't say much more...
EDIT:
Make your point class store optional values:
class Point
{
private Optional<String> x;
private Optional<String> y;
public Optional<String> getX () { //Here can not use Optional<String>
return this.x;
}
public Optional<String> getY () {
return this.y;
}
public Point(String x, String y) {
this.x = ofNullable(x);
this.y = ofNullable(y);
}
}
Then:
Point point = new Point(null, "14.2");
if(point.getX().isPresent()) {
this.xCoordinate = point.getX();
}
if(point.getY().isPresent()) {
this.yCoordinate = point.getY();
}
Related
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;
}
}
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.
My class details attributes of restaurants downtown, said attributes being x/y locations and rank. The problem is, whenever I run the program It throws an error, saying that non-abstract class "Downtown" does not override abstract method "compareTo". I cannot make this class abstract because I need to initialise the object outside this block of code. Where does my program go wrong? Is there a problem with my compareTo implementation? Any suggestions will be much appreciated.
public class Downtown implements Comparable<Downtown> {//Throws error on this line
private int x;
private int y;
private int rank;
public Downtown(int x, int y, int rank) {
this.x = x;
this.y = y;
this.rank = rank;
}
//Appropriate setters and getters for x , y and rank
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 int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int compareTo(Downtown p1, Downtown p2)//Actual comparison
{
// This is so that the sort goes x first, y second and rank last
// First by x- stop if this gives a result.
int xResult = Integer.compare(p1.getX(),p1.getX());
if (xResult != 0)
{
return xResult;
}
// Next by y
int yResult = Integer.compare(p1.getY(),p2.getY());
if (yResult != 0)
{
return yResult;
}
// Finally by rank
return Integer.compare(p1.getRank(),p2.getRank());
}
#Override
public String toString() {
return "["+x+' '+y+' '+rank+' '+"]";
}
Java's Comparable<T> interface defines compareTo method as follows:
int compareTo(T o);
This means that the method must take one parameter; the other parameter is the object itself, i.e. this. You need to implement this one-argument method in place of your two-argument method to fix this problem.
Compiler will help you figure out issues like this by using #Override annotation on your method:
#Override // Issues an error
public int compareTo(Downtown p1, Downtown p2)
#Override // Compiles fine
public int compareTo(Downtown other)
The compareTo method should compare the current object (this) to just one other. It shouldn't have two parameters for comparison. You could write your method like this.
public int compareTo(Downtown p2)//Actual comparison
{
// This is so that the sort goes x first, y second and rank last
// First by x- stop if this gives a result.
int xResult = Integer.compare(getX(),p2.getX());
if (xResult != 0)
{
return xResult;
}
// Next by y
int yResult = Integer.compare(getY(),p2.getY());
if (yResult != 0)
{
return yResult;
}
// Finally by rank
return Integer.compare(getRank(),p2.getRank());
}
Notice how I've replace all the calls on p1 to calls on the current object.
is it possible to get the final parameter values from an anonymous class? Using reflection or anything else?
This example is of course all made up:
final String x = "Param1";
final String y = "Param2";
ITest<String> iTest = new ITest<String>() {
#Override
public String execute() {
return t.testMethod(x, y);
}
};
// Get values or x and y from iTest here?
So this is your code:
ITest<String> iTest = new ITest<String>() {
#Override
public String execute() {
return testMethod(x, y);
}
};
Try defining ITest like so:
public class ITest {
int x;
int y;
public testMethod(int x, int y) {
this.x = x; this.y = y;
}
// execute somewhere
}
I haven't tried this myself, but I believe that the values of x and y are copied into autogenerated fields in the anonymous class instance. Try this:
for (Field field : iTest.getClass().getDeclaredFields()) {
field.setAccessible(true);
System.out.println(field.getName() + ": " + field.get(iTest));
}
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.