Here is the thing.. I want to draw some lines into some charts for a website.
These charts sometimes will have sometimes one or two lines.. but sometimes a few more where each is defined by an arbitrary mathematical function.
As for now, I only know this possibility to draw e.g. three lines:
public class ArbitraryFunctionData {
private double x1;
private double x2;
private double x3;
private double y;
public ArbitraryFunctionData(double x1, doouble x2, double x3, double y) {
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.y = y;
}
public double getX1() {
return x1;
}
public double getX2() {
return x2;
}
public double getX3() {
return x3;
}
public double getY() {
return y;
}
public void setX1(double x1) {
this.x1 = x1;
}
public void setX2(double x2) {
this.x2 = x2;
}
public void setX3(double x3) {
this.x3 = x3;
}
public void setY(double y) {
this.y = y;
}
}
Somewhere there is a need to define this interface:
public interface ArbitraryFunctionAccess extends
PropertyAccess<ArbitraryFunctionData> {
ValueProvider<ArbitraryFunctionData, Double> x1();
ValueProvider<ArbitraryFunctionData, Double> x2();
ValueProvider<ArbitraryFunctionData, Double> x3();
#Path("x")
ModelKeyProvider<ArbitraryFunctionData> xKey();
}
So I can add these access function as fields to the chart:
horizontalAxis.addField(arbFuncAccess.x1());
horizontalAxis.addField(arbFuncAccess.x2());
horizontalAxis.addField(arbFuncAccess.x3());
This is a very uncomfortable way to create a chart. Is there any better way to do this?
ArbitraryFunctionData needs to be pre defined and one needs to add every single access method by hand. I'd rather do something like that:
ArbitraryFunction f1 = new ArbitraryFunction(0, 5, 0, 5) {
#Override
public double f(double x) {
return x+1;
}
};
ArbitraryFunction f2 = new ArbitraryFunction(0, 5, 0, 5) {
#Override
public double f(double x) {
return x+2;
}
};
store.add(0, f1.getData()); // a line
store.add(1, f2.getData()); // another line
where ArbitraryFunctions function public double f(double x) needs to be overwritten and ArbitraryFunction.getData() is defined as public List<ArbitraryFunctionData> getData(). This would add more dynamic to the whole thing but the problem is, that I can not add the fields to the chart since they need to be pre-defined in public interface ArbitraryFunctionAccess.
I hope I described my need properly. Does anyone know a possible solution to this?
PropertyAccess isn't the point here - ValueProvider is. The PropertyAccess type is just a nice way to auto-generate a bunch of really boring ValueProvider/ModelKeyProvider/LabelProvider types that you could easily do by hand. Your time is valuable, so we don't make you do it by hand.
This means that you can make a hand-made implementation of ValueProvider that does whatever you want it to. I'm not really clear what 0,5,0,5 means or what f1.getData() is intended to return/do, but you could define f1 as a ValueProvider type that can find objects in that list.
public class AribtraryDataVP implements
ValueProvider<ArbitraryFunctionData, Double>() {
private final int index;
public AribtraryDataVP(int index) {
this.index = index;
}
public Double getValue(ArbitraryFunctionData object) {
return object.getData().get(index);
}
public void setValue(ArbtraryFunctionData object, Double value) {
object.getData().set(index, object);
}
public String getPath() {
return "data[" + index + "]";
}
}
The purpose of the ValueProvider type is to allow access to reading and writing properties of objects. In your case, you probably don't care about setValue, but it is usually good to either implement it or at least throw an exception so you know that someone tried to call it and it didn't work. Likewise, the getPath method is used to tell the difference between properties, sometimes for debugging purposes, and sometimes for sorting or filtering on the server, which needs the name of the property it is supposed to sort/filter. Again, probably not needed in your case, but it is usually good to get right.
I think this then will do what you were trying to do, adding those ValueProviders (i.e. properties, now mapped to list items) to the chart.
//f1, f2
axis.addField(new AribtraryDataVP(1));
axis.addField(new AribtraryDataVP(2));
Related
If I try to inherit a builder to add more options, I get an unwanted requirement that options be set in a certain order. For example, let me build two builders for class java.awt.geom.Point2D. In the base builder, we can only set the X, but in the second builder, which extends the base builder, we can also set Y:
private static class PointBuilder{
private double x = 0.0;
protected double y = 0.0;
PointBuilder withX(double x) {
this.x = x;
return this;
}
Point2D build() {
return new Point2D.Double(x, y);
}
}
private static class PointBuilderWithY extends PointBuilder {
PointBuilder withY(double y) {
this.y = y;
return this;
}
}
public static void main(String[] args) {
Point2D pt1 = new PointBuilder()
.withX(5.0)
// .withY(3.0) // withY() doesn't compile, which is the intended behavior
.build();
// I can use a PointBuilderWithY only if I set the Y option first.
Point2D pt2 = new PointBuilderWithY()
.withY(3.0)
.withX(5.0)
.build();
// If I set the X option first, the Y option doesn't build!
Point2D pt3 = new PointBuilderWithY()
.withX(5.0)
.withY(3.0) // Won't compile! withX() didn't return a PointBuilderWithY
.build();
System.out.println(pt1);
System.out.println(pt2);
System.out.println(pt3);
}
If I call withX() before withY(), the withY() method won't compile, because the withX() method didn't return the PointBuilderWithY class. The base PointBuilder class doesn't have the withY() method.
I know that I can add an abstract withY() method to the base class, but that defeats the point. I want to limit the use of the withY() method to only those objects that need it. In other words, I want the compiler to enforce the restriction that withY() can't be called when using the first PointBuilder. At the same time, I don't want to tell my users that the options must be specified in a certain order, because that would be confusing. I prefer to write foolproof systems. Users expect to specify options in any order, which makes the class easier to use.
Is there a way to do this?
In PointBuilderWithY override all of PointBuilder's methods to return PointerBuilderWithY instances.
private static class PointBuilderWithY extends PointBuilder {
#Override
PointBuilderWithY withX(double x) {
return (PointBuilderWithY) super.withX(x);
}
PointBuilderWithY withY(double y) {
this.y = y;
return this;
}
}
My teacher wanted us to create program to compute the bills of our home. In java we were just going over objects and classes so I made
class Bills{
Bills... etc
The problem I am having is I dont know how to get a total of two methods that take in a value.
public double getWifepay(double x){
return x;
}
public double getHusbandpay(double y){
return y;
}
public double getTotalmoney(){
???
}
Your methods should probably just return some value that is stored within the object. So you would have something like:
public double getWifePay(){
return wifePay;
}
public double getHusbandPay(){
return husbandPay;
}
And
public double getTotalmoney(){
return getWifePay() + getHusbandPay();
}
and then you probably would want to write some setter methods like:
public void setWifePay(double wifePay) {
this.wifePay = wifePay;
}
public void setHusbandPay(double husbandPay) {
this.husbandPay = husbandPay;
}
And in your class definition you should have declared these fields:
public class Bills {
double wifePay;
double husbandPay;
// And then the methods from above
}
Create the previous two method (getwifepay, gethusbandpay) as static and call them in getTotalmoney function with class name. suppose class name is A so call as A.getwifePay(value)
Not sure I understand your model classes, but as you mention, for the "getTotalMoney" method to return the sum, the elements (the numbers in this case) should be given as parameters.
On the other hand, your "getWifepay" and "getHusbandpay" methods don't make much sense, as they are returning the same parameter which is given.
With all of this, you would need to have the method "getTotalmoney" call the other two and then make the sum, like this:
public double getWifepay(){
return x;
}
public double getHusbandpay(){
return y;
}
public double getTotalmoney(){
getWifepay() + getHusbandpay();
}
Finally, I suppose that these methods are within a given class (you mentioned Bill), making it maybe something like this:
class Bill {
private double x;
private double y;
private double getWifepay(){
return x;
}
private double getHusbandpay(){
return y;
}
public double getTotalmoney(){
getWifepay() + getHusbandpay();
}
}
Hope that solves your problem.
I want a Animations class that can be reused through different projects. The problem is how I let the class change another object's members (such as position). Here is a very simplified version of how it would operate and what it can do.
public class Animation() {
private float currValue, targetValue, duration;
public Animation(currValue, targetValue, duration) {
this.currValue = currValue;
this.targetValue = targetValue;
this.duration = duration;
}
public void update() {
// Here I would update its currValue based on duration and target
}
}
So when I want to animate let's say a rectangle's position I would do:
class Rectangle {
private float x, y;
private Animation a;
public Rectangle (x, y) {
this.x = x;
this.y = y;
this.a = new Animation(x, 100, 1000); // Duration in ms
}
public void update() {
a.update(); // Update animation
}
}
Obviously this does not work, because Animation does not update Rectangle's x value. Only one solution comes to mind, and that is passing in the instance of Rectangle and the field name "x" and then use the Reflection API to update the value. But that seems like a pretty poor solution.
Any suggestions? Should I design my code differently?
Reflection is not necessarily a poor solution in this case. In fact, it's a very general solution that allows elegant code on the client side. But of course, one should be aware of the caveats of using reflection in general.
A very pragmatic approach of such an animation would be to "factor out" what the animation actually does: Namely changing some float value, in your case. So one way of separating the "client" code and the implementation could be the following:
interface FloatSetter {
void setFloat(float f);
}
public class Animation
{
private float currValue, targetValue, duration;
private FloatSetter floatSetter;
public Animation(
float currValue, float targetValue, float duration,
FloatSetter floatSetter)
{
this.currValue = currValue;
this.targetValue = targetValue;
this.duration = duration;
this.floatSetter = floatSetter;
}
public void update()
{
...
floatSetter.setFloat(currValue);
}
}
Then you can pass an appropriate implementation of FloatSetter to your Animation - probably via an anonymous inner class:
class Rectangle
{
private float x, y;
private Animation a;
public Rectangle(float fx, float fy) {
this.x = fx;
this.y = fy;
FloatSetter floatSetter = new FloatSetter()
{
#Override
public void setFloat(float f)
{
this.x = f;
}
});
this.a = new Animation(x, 100, 1000, floatSetter);
}
public void update() {
a.update(); // Update animation
}
}
BTW: Depending on what you are going to achieve, I'd recommend to not put the Animation instance into the Rectangle. But I assume that this is just a sketch to show your intention.
Important : You should definitiely have a look at the "Timing Framework": https://java.net/projects/timingframework . It is the accompanying code for chapters of the book "Filthy Rich Clients" ( http://filthyrichclients.org/ ) by Chet Haase and Romain Guy, and they certainly know their stuff. The library is a very sophisticated and flexible implementation of what you obviously want to achieve there. (They also support a generic "PropertySetter" that uses reflection (https://java.net/projects/timingframework/sources/svn/content/trunk/timingframework-core/src/main/java/org/jdesktop/core/animation/timing/PropertySetter.java?rev=423 ), but this is just one helper class to define a general "TimingTarget", which is the sophisticated version of the "FloatSetter" that I sketched above).
I'm currently working on a game written in Java.
At the moment I'm stuck finding an easy way to store my GameObjects (Player, Enemies, and so on...) so that I can access them by their coordinates while still being able to move them easily.
I already tried Multidimensional Arrays, which is nice, but won't let me move my Objects easily. I'd have to physically move the Object in the array every time it moves.
Then I tried "normal" Arrays, which lets you move things easily, just increase the objects x, y or z value, but won't allow me to access Objects by coordinates without iterating through the whole array.
Right now, i'm trying to find a compromise that allows me to have both.
Thanks in advance,
//265
The simple solution is to use both forms at the same time. Store the coordinates in your GameObject instances, but also simultaneously cache them in your 3D array. The array should preferably be encapsulated in an object that provides method to update and query it. Something like this:
public class GameObjectDatabase implements LocationChangeListener {
private int [] [] [] data;
private Set<GameObjects> objects;
...
public GameObject gameObjectAt(int x, int y, int z) {
return data[x][y][z];
}
#Override
public void positionUpdated(GameObject obj, int oldX, int oldY, int oldZ) {
....
}
}
Why the listener and the overridden method? Because it's not really your GameObject's job to update this data - it's the responsibility of the GameObjectDatabase. So, ideally, your GameObject should allow to register listeners in a Set and call their positionUpdated methods every time its location changes.
All game objects that have a position (player, enemies etc) should have an internal reference to their position eg;
class Position {
int x;
int y;
}
interface Positionable {
Position getPosition();
void setPosition(int x, int y, GameArea area);
}
class Player implements Positionable {
//stuff
}
class Enemy implements Positionable {
//stuff
}
You can then have a class representing your game area;
class GameArea {
Positionable[][] grid;
List<Positionable> gameObjects;
public Positionable getByLocation(int x, int y) {
return grid[x][y];
}
public void setAtLocation(int x, int y, Positionable p) {
grid[x][y] = p;
}
public List<Positionable> getAll() {
return gameObjects;
}
}
This allows you to access by position and iterate over all objects. When a game object moves it needs to update its position internally and explicitly update the GameArea, as shown in the below example setPosition() implementation.
void setPosition(int x, int y, GameArea area) {
area.setAtLocation(this.x, this.y, null);
area.setAtLocation(x, y, this);
this.x = x;
this.y = y;
}
Here is a programming test used in a job interview. I find it has a very strange non-OO perspective and wonder why anyone would approach a constructor from this perspective. As a very experienced Java programmer, I immediately question the ability of the individual who wrote this code and the strange perspective of the question.
I find these strange out of context questions on interviews disturbing. I would love feedback from other experienced OO Java programmers.
Complete the Solver constructor so that a call to solveAll return a list with 2 values
including the square root and the inverse of the integer passed as parameter.
public interface MathFunction {
double calculate(double x);
}
public class Solver {
private List<MathFunction> functionList;
public Solver() {
//Complete here
}
public List<Double> solveAll(double x) {
List<Double> result = new ArrayList<Double>();
for (MathFunction function : this.functionList) {
result.add(new Double(function.calculate(x)));
}
return result;
}
}
This is testing your design patterns, by using the simplest possible method. I think this could be the Strategy (or some other behavioural pattern). See these:
http://en.wikipedia.org/wiki/Strategy_pattern
http://en.wikipedia.org/wiki/Behavioral_pattern
If you are going for a Java interview, you should be able to identify the design pattern they are hinting at and that should prevent you from being too unsettled!
To answer the question, create two classes that implement MathFunction as required, then create two instances and store them in functionList.
The point here is not 'can you do calculations in this strange way', it is 'can you identify design patterns'.
I agree that it's confusing and over-engineered.
But I do think the code is reasonably object-oriented. It's an instance of the strategy pattern. The code that generates a list of answers doesn't care how the answers are calculated - the two concerns are separated and a different calculation strategy could be applied without having to touch the code that generates the list.
To make the class more useful, these functions should be passed in from the outside (i.e. dependency injection) rather than being instantiated in the constructor.
You know the answer, I assume, but for what it's worth...
public Solver() {
functionList = new ArrayList<MathFunction>();
functionList.add(new MathFunction() {
#Override
public double calculate(double x) {
return 1d/x;
}
});
functionList.add(new MathFunction() {
#Override
public double calculate(double x) {
return Math.sqrt(x);
}
});
}
IMHO, it is indeed a strange approach. The name Solver is generic, it shouldn't implement specific operations by default. However, maybe that was part of the interview? Part one: simply fulfill the request. Part two: say that it is strange to do so.
I would say that a much nicer approach would be to have an addMathFunction(MathFunction mf) method. And if wanted, to create subclasses that extend the Solver class and add MathFunctions in their constructor.
I think they wanted you to add two items in the functionlist. Each one would implement the MathFunction interface, one for the square root and one for the inverse.
The prboblem lies in the details:
1- You have a function which returns 2 values because it does two different things, that is bad
2- If you want to have this "do-it-all" class,m it would be interesting to receive the Mathfunctions as a parameter so you can do any sort of MathFunctions, the MathFunctions would be parameterizable
Here's my solution. This is a simple illustration of a factory class.
public Solver() {
functionList = new ArrayList<MathFunction>();
MathFunction sqrt = new MathFunction() {
#Override
public double calculate(double x) {
return Math.sqrt(x);
}
};
functionList.add(sqrt);
MathFunction inverse = new MathFunction() {
#Override
public double calculate(double x) {
return 1.0D / x;
}
};
functionList.add(inverse);
}
This question shows two things:
Whether the programmer understands math terms like inverse.
Whether the programmer understands that instances of interfaces or classes can be stored in a list, and iterated over later.
While I agree that this probably isn't the best way, or most OO way to do this, I would have to assume that the point of this exercise is to see how well you understand Inheritance, Interfaces and maybe anonymous inner classes. That's the only thing I can figure.
Ok, I coded the solution to my own question. My instinct that nothing should be in the constructor seems to be correct. The functionList is not static so you need an instance to initialize it. It specifies integer so I round to integer. The inverse function is not advanced math in any way.
import java.util.ArrayList;
import java.util.List;
import java.lang.Math;
public class Solver {
private List<MathFunction> functionList = new ArrayList<MathFunction>();;
public Solver() {
// Complete here
}
public void initFunctionList() {
MathFunction functionSquareRoot = new MathFunction(){
#Override
public double calculate(double x) {
return (x<0 ? 0: Math.sqrt(x)); // maybe we need throw an exception here for negative numbers, but we'll just set it to 0
}};
MathFunction functionInverse = new MathFunction(){
#Override
public double calculate(double x) {
return (x!=0.0 ? 1/x : 0);
}
};
functionList.add(functionSquareRoot);
functionList.add(functionInverse);
}
public List<Double> solveAll(double x) {
List<Double> result = new ArrayList<Double>();
for (MathFunction function : this.functionList) {
result.add(new Double(function.calculate(x)));
}
return result;
}
}
public interface MathFunction {
double calculate(double x);
}
public class TestSolver {
/**
* #param args
*/
public static void main(String[] args) {
Solver s = new Solver();
s.initFunctionList();
System.out.println(s.solveAll(16.0));
}
}
I mislead myself the constructor can be
public Solver() {
// Complete here
MathFunction functionSquareRoot = new MathFunction(){
#Override
public double calculate(double x) {
return (x<0 ? 0: Math.sqrt(x)); // maybe we need throw an exception here for negative numbers, but we'll just set it to 0
}};
MathFunction functionInverse = new MathFunction(){
#Override
public double calculate(double x) {
return (x!=0.0 ? 1/x : 0);
}
};
functionList.add(functionSquareRoot);
functionList.add(functionInverse);
}
Somewhat contrived, seems closer to the decorator pattern to me.
Not sure what I would say during an interview but here is how I would code it:
package math;
import java.util.ArrayList;
import java.util.List;
public class DecoratorMath
{
interface MathFunction
{
double calculate(double x);
}
public static void main(String[] args)
{
DecoratorMath decoratorMath = new DecoratorMath();
decoratorMath.go();
}
public void go()
{
Solver solver = new Solver();
decorate(solver);
List<Double> results = solver.solveAll(02);
for (Double d :results)
{
System.out.println(d);
}
}
public void decorate(Solver solver)
{
solver.addFunction(new MathFunction()
{
#Override
public double calculate(double x)
{
return Math.sqrt(x);
}
});
solver.addFunction(new MathFunction()
{
#Override
public double calculate(double x)
{
return 1d/x;
}
});
}
class Solver
{
private List<MathFunction> mathFunctions = new ArrayList<MathFunction>();
public void addFunction(MathFunction mathFunction)
{
mathFunctions.add(mathFunction);
}
public List<Double> solveAll(double x)
{
List<Double> result = new ArrayList<Double>();
for (MathFunction function : mathFunctions)
{
result.add(new Double(function.calculate(x)));
}
return result;
}
}
}
Doing this all within the Constructor is just poor practice. Anyway my all-in-one solution.
import java.util.*;
import java.math.*;
//sqrt / inverse
public class Solver{
private List<MathFunction> functionList;
public interface MathFunction{
double calculate(double x);
}
class X implements MathFunction {
public double calculate(double x) {
return Math.sqrt(x);
}
}
class Y implements MathFunction {
public double calculate(double y) {
return 1/y;
}
}
public Solver(){
//here
functionList = new ArrayList<MathFunction>();
MathFunction f = (MathFunction) new X();
functionList.add(f);
MathFunction f2 = (MathFunction) new Y();
functionList.add(f2);
}
public List<Double> solveAll(double x){
List<Double> result=new ArrayList<Double>();
for (MathFunction function : this.functionList){
result.add(new Double(function.calculate(x)));
}
return result;
}
public static void main(String... args) {
System.out.println("result="+new Solver().solveAll(123));
}
}