Making java wait until a property is called for? - java

I recently started working with JOGL, so I made a vector class. Inside this class, I used the line
public Vector unit=new Vector(x/length,y/length,z/length);
To find the unit vector. And of course, this causes a stackoverflow. Is there any way to make java wait for unit to be called before running this or will I have to make unit a method?

I woukld personally create a second constructor, which calculates the unit vector and sets its own unit vector to itself. You should ideally use private values and a get method as Ernest suggests. The reason for this is that otherwise other classes can simply overwrite the x,y,z, etc. values if they have access to one of your objects. Java has a tradition of using final classes for pure data storage. See the String class for example. You can't modify an existing String, only create a new String. Once created, a String remains the same. For your purposes it might not matter much, but in a different context it may cause your application to misbehave, if your class is used by someone who doesn't have a clue. It might even be a security risk in some cases.
You could simply ignore this and access the variables directly, and enjoy the less cluttered code and small performance increase. But I would still suggest knowing what the problem is for the future.
Anyway, below is my suggested code for solving the unit vector problem, minus getter methods.
import java.lang.Math;
class Vector{
public double x,y,z,length;
public Vector unit;
public static void main(String[]s){
new Vector(5,5,5);
}
public Vector(double x, double y, double z){
this.length = Math.sqrt(x*x + y*y + z*z);
this.x=x;
this.y=y;
this.z=z;
this.unit = new Vector(x/length, y/length, z/length, true);
}
private Vector(double x, double y, double z, boolean isUnitVector){
// Temp variable for calculating the length
double length = Math.sqrt(x*x + y*y + z*z);
if (isUnitVector){
this.length = 1;
this.x=x/length;
this.y=y/length;
this.z=z/length;
this.unit = this;
}else{
this.length = Math.sqrt(x*x + y*y + z*z);
this.x=x;
this.y=y;
this.z=z;
this.unit = new Vector(x/length, y/length, z/length, true);
}
}
}
I'm not entirely happy with the code duplication between the constructors that follows from the boolean argument. In practice, I would probably create a factory class, VectorFactory with one static method, whose only job is to create Vector objects. Or maybe just use Java's own javax.vecmath.Vector3d and related classes.

Yes, this is easy enough, but you'll need to fix your design a bit. Most importantly, as is almost always the case with all member variables, unit should be private, and all access to it should be through a method named something like getUnit(). Then, you simply write getUnit() to check whether unit has been initialized or not:
public synchronized Vector getUnit() {
if (unit == null)
unit = new Vector(x/length,y/length,z/length);
return unit;
}
I've made this method synchronized so that you'll avoid any problems if two different threads call getUnit() at around the same time, and unit hasn't been initialized yet.

I propose a constructor which decides itself whether it is a unit vector or not. If it is a unit vector, then unit points to itself. This will break the recursion of the constructor.
The only problem might be numbers where length is not exactly 1.0 due to rounding errors.
public class Vector {
public double x, y, z;
public Vector unit;
public Vector(double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
double length = calcLength(x, y, z);
if( length == 1.0 ) // perhaps add a little fuzz factor.
this.unit = this;
else
this.unit = new Vector(x/length, y/length, z/length);
}
}

Related

How can I create a getter method and a setter method for a multidimensionnal array?

To begin, sorry for my English, I'm French.
Here's the problem I'm trying to solve by writing this problem in a mathematical notation:
I have couples of coordinates that look like this: (x, y)
An = {(Xn;Yn)}
array[An][(Xn;Yn)] = {{X1;Y1}{X2;Y2}...{Xz;Yz}};
In my program, I need to create a getter and setter for the multidimensionnal array.
This is my code:
//Infos for animations of objects
//Sorting
Random random1 = new Random();
int obscMin=0, obscMax=4; //I sort them to know how many obstacles will have to be created. obsc is the obstacle
int nbreObsc = obscMin + random1.nextInt(obscMax - obscMin); //nbreObsc is the number of obstacles
//End of sorting
/*Here's the model of a table:
A couple: An={(Xn;Yn)}
Tableau1[An][(Xn;Yn)]={{X1;Y1}{X2;Y2}...{Xz;Yz}};*/
float posObsc [] []=new float [nbreObsc] [2]; //New table, which will contain the positions of the obstacles
//Obstacle position getter and setter
public float[][] getPosObsc(){//getters
return posObsc;
}
public void setPosObsc(float[][] posObsc){//setters
this.posObsc=posObsc;
}
//End of obstacle position getter and setter
protected boolean detruireObsc=false; //"detruireObsc" means "destroyObstacle"
//Algorithm that defines the movement of obstacles
protected void obscDeplacemt(){
for(int i=1;i<=nbreObsc;i++){
//Sorting to determine the Xs
float ordMin=0,ordMax=width;
float ordObsc = ordMin + (float)Math.random() * (ordMax - ordMin); //ordObsc means obstacleXPosition
setPosObsc( posObsc [i][0]);
//End of sorting
}
}
//End of obstacle movement algorithm
Here's the error I get from eclipse:
The method setPosObsc(float[][]) in the type Activity01Jeux.RenderViewJoueur is not applicable for the arguments (float)
The line of code:
setPosObsc( posObsc [i][0]);
Is calling the setPosObsc() method with a single float element from the array of arrays. But the method takes an array of arrays.
To make the code compile, you could write:
setPosObsc(posObsc);
Though that may not be what you want! If you are trying to write a method that puts a float into the array at a particular point, you will need something like this:
void setObstacleAt(int obstacleIndex, int boundaryIndex, float shiftDistance) {
posObsc[obstacleIndex][boundaryIndex] = shiftDistance;
}
I'm making a wild guess at what your array contains.
As a side note, rather than writing comments to explain the method names, you might consider using longer or more precise method names without abbreviations. In Java there is no practical limit to the length of variable and method names.
By the way, well done for having the courage to write to StackOverflow in English when it's not your first language. I had no trouble understanding your question even before Runemoro's edits.
Your getter and setter methods are fine. The error is because in the last line of code in obscDeplacemt(), you are calling setPosObsc(posObscp[i][0]). posObscp[i][0] will give you a float, when your setter method needs an array of float in the parameter in order for it to work. Good luck!
Looks like what you're trying to do is:
posObsc[i][0] = ordObsc;
There's no need to use a setter if you're in the same class.
If you want to be able to externally set an element value by index (instead of overwriting the whole array), there are two ways to go about it:
1) (Not recommended)
Since you're exposing the whole array in your getter, you can theoretically call
getPostObsc()[i][0] = ordObsc;
2) (Recommended)
Change your getter and setter to
public float getPosObsc(int x, int y){
return posObsc[x][y];
}
public void setPosObsc(int x, int y, float val){
this.posObsc[x][y] = val;
}
Now you can update an element using the setter with an index:
setPostObsc(i, 0, ordObsc);

What's the difference between these two constructors in java ? (Memory)

here in this code
public class Base {
int length, breadth, height;
Base(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
}
and
Base(int l, int b, int h) {
this.length = l;
this.breadth = b;
this.height = h;
}
here what's the difference between this two constructors intialization?
which method is highly preferred?
how it varies in terms of memory allocation?
There's no difference. In the first constructor you just omit this while in the second you explicitly specify it. Generated bytecode is exactly the same (you can check it). It's just a matter of style if you want to put this or not, unless the field has the same name as the parameter, in which case this is mandatory to avoid ambiguity, for example:
Base(int length,int breadth,int height) {
this.length = length;
this.breadth = breadth;
this.height = height;
}
(Please use spaces wisely, it makes your code more readable).
They are the same.
A difference would be if you write this:
Base(int length, int breadth, int height)
{
this.length=length;
this.breadth=breadth;
this.height=height;
}
because there are two variables named length etc.
Both are same. In the first case, compiler will implicitly add this keyword while compiling it.
The only difference is that seconds seems more readable. It easily differentiates member variables from local ones. Generally this comes in handy to refer member variables when local variables shadow them.
There is no difference, because this is implicitly added to the first constructor. In Java in terms of construtors there is a convention to use the second approach, because it's more readable and not as error prone as the first approach.
There is also no difference in memory allocation, because the byte code it exactly the same.

Calculating math in GPS format

I'm making a Android Application to calculate Math in GPS Format.
Example:
Given
N 48°44.(30x4) E 019°08.[(13x31)+16]
the App calculates it, and result is:
N 48°44.120 E 019°08.419
Is it possible to do this?
I searched for plugins and solutions, but it's all just for math strings like as "14 + 6".
I am assuming you are working in Java as it is tagged in your question.
You could create a new public class for your GPS coordinates, and store the actual value of the coordinate in the lowest division, which according to your example appears to be minutes or seconds. This allows you to store the value as an int or a double with whatever precision you wish. You could then create a set of private and public methods to complete your mathematical operations and others to display your values in the appropriate fashion:
public class GPSCoordinate {
private double verticalcoord;
private double horizontalcoord;
//Constructors
GPSCoordinate(){
setVertical(0);
setHorizontal(0);
}
GPSCoordinate(double vert, double horiz){
setVertical(vert);
setHorizontal(horiz);
}
//Display methods
public String verticalString(){
return ((int)verticalcoord / 60) + "°" + (verticalcoord - ((int)verticalcoord / 60) *60);
}
public String horizontalString(){
return ((int)horizontalcoord / 60) + "°" + (horizontalcoord - ((int)horizontalcoord / 60) *60);
}
//Setting Methods
public void setVertical(double x){
this.verticalcoord = x;
}
public void setHorizontal(double x){
this.horizontalcoord = x;
}
//Math Methods
public void addMinutesVertical(double x){
this.verticalcoord += x;
}
}
This will allow you to initiate an instance in your main code with a given GPS coordinate, and then you can call your math functions on it.
GPSCoordinate coord1 = new GPSCoordinate(567.23, 245);
coord1.addMinutesVertical(50);
coord1.otherMathFunction(50 * 30);
You will, of course, need to refine the above to make it fit your project. If this isn't helpful, please provide more specifics and I'll see if I can think of anything else that might fit what your looking for.
Can't you just substring the whole thing and search for the expression in the brackets? Then it's just a matter of simple calculation. If I understood the question correctly. The gps data doesn't look like an ordinary expression, so you can't appy math() directly.

When to use nested class [duplicate]

This question already has answers here:
When to use nested class?
(3 answers)
Closed 9 years ago.
If a function returns 2 values, for example: min/max in array or for example, x and y axis of a point, it would need to create an object, since a function cannot return 2 values.
Now, consider a client whose 'only' function is to use getters in the returned object and print.
AND
The returned object say MinMax or Point object is created only by one class,
Should we use a nested class (eg: MinMax, Point can be nested class) or use a top level class?
This is a generic question - below is just one such example related to the question. Please done answer related to the code sample as it is a very generic question not bound to the sample code.
Should the Point class be inner class returned similar to the way itr is returned by arraylist ?
class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
public class IntersectionOf2Lines {
public static Point calculateIntersection(Line line1, Line line2) {
int x = (line2.getConstant() - line1.getConstant()) / (line1.getSlope() - line2.getSlope());
int y = line1.getSlope() * x + line1.getConstant();
return new Point(x, y);
}
Line line3 = new Line(2, 2);
Line line4 = new Line(3, 2);
Point p1 = IntersectionOf2Lines.calculateIntersection(line3, line4);
System.out.println("Expected: x = 0, Actual x = " + p1.getX() + " Expected y=2, Actual y = " + p1.getY());
IMHO it is a matter of style. I would look at it from the point of view of someone who is reading your code from the first time. Which classes do you want to make obvious and which ones do you want to group away and they only need to read when they get into the details.
BTW: A nested class need to be nested inside the scope of another class, not just in the same class file as it is in your example.

Add numbers with the word "add"

I am writing to offer an application in Java right now and instead of using the operator "+", the user of the application can literally use the word "add" to add two numbers together.
I'm quite stuck on how to do this because I can't really use a method in order to complete the function considering I'd have to type "add()" rather than just "add". Unless there is a way to execute a method without the parentheses. Would I have to write a completely new class or is there an easier way to do this?
Just a little explanation on what you could do based on what the user enters:
int x = get it from the user;
int y = get it from the user;
string operation = get it from the user;
Create separate methods for the operations (i.e add(int x, int y), multiply(int x, int y), etc..)
Then create a method thag gets the values (x, y, string) say.. you can call it calculate(int x, int y, string operation)
Then in the calculuate method have a switch statement:
switch(operation)
{
case "add":
add(x,y);
break;
case "multiply":
multiply(x,y);
break;
etc...
}
Well, got you something to think about :).
There's no way to do this in Java. You have two options:
1)Use a preprocessor.
2)Write it in a different language. You can write things in other languages and still have it compatible with Java classes and libraries.
The consensus in comments seems to be 'Why would you want to do this? It is slow and cumbersome'. While the latter part is true, it is commonly done. See ScriptEngine as an example. Here is a demo of the JavaScript ScriptEngine in an applet.
The reader might note that ScriptEngine is an interface, suggesting an answer of 'implement your own script engine, based on the rules required'. Whether or not it is a good idea to create another scripting language, is left as an exercise for the reader.
(An expansion on the idea presented by user710502)
You can use reflection.
double a = Double.parseDouble(some user input);
double b = Double.parseDouble(some user input);
String operation = some user input; // i.e. "add", "subtract"
Method operator = Calculations.class.getMethod(operation, double.class, double.class);
// NoSuchMethodException is thrown if method of operation name isn't found
double result = (Double) operator.invoke(null, a, b);
In some sort of calculations class:
public static double add(double a, double b) {
return a + b;
}
public static double subtract(double a, double b) {
return a - b;
}
// and so forth

Categories

Resources