I'm having trouble accessing a variable of a class I have created within a for loop.
The class I have created is fairly simple and just combines a vector and a double value.
public class VectorDistance
{
Vector2d v;
double d;
public VectorDistance(Vector2d v, double d)
{
this.v = v;
this.d = d;
}
}
and within a method in another class which inherits an ArrayList of these vector distances, I'm trying to access the variables of it but it doesn't seem to want to access it. But for whatever reason it won't let me access it. I've tried value.get(0) etc but that does not work. Any help would be greatly appreciated. It is declared as an ArrayList with type VectorDistance throughout the code.
public String NewPositionCheck(Vector2d checkPosition, int blockSize, Types.ACTIONS fromPrevious, List<Types.ACTIONS> previousPositions, ArrayList<Observation>[][] grid, int i, ArrayList <VectorDistance> vd)
{
double closest = Double.MAX_VALUE;
for (VectorDistance value : vd)
{
}
}
all i want is to find the smallest value in the ArrayList, by comparing its double value (d) with value "closest" and then store that position as an integer (which i forgot to add)
You have to declare them public, to access them outside of its class
public Vector2d v;
public double d;
Or much better solution is to create getters/setters (just google it)
Also - modern IDE like netbeans, eclipse etc. even have option to create getters/setters for you)
You have to specify access modifier as public as below:
public class VectorDistance
{
public Vector2d v;
public double d;
public VectorDistance(Vector2d v, double d)
{
this.v = v;
this.d = d;
}
}
More professional way would be declaring access methods, with the name getSomething() or setSomething(ValueType val)
Related
Consider this:
public class Test {
public static int numberOfInstances = 0;
public int myInstanceID;
public String myInstanceName;
The static variable doesn't need to be called within an instance, it's available everywhere like this:
Test.numberOfInstances
When creating an instance, I only do this into my constructor:
public Test(int id, String name) {
myInstanceID = id;
myInstanceName = name;
numberOfInstances += 1;
}
I've recently discovered the this keyword and have noted some of its uses:
public Test() {
this(numberOfInstances + 1, "newInstance");
numberOfInstances += 1;
}
From what I've noticed, the this keyword allows you to call another one of the class' constructors. It also allows you to do this:
public Test(int x, int y) {
this.x = x;
this.y = y;
}
With java, I highly disagree with this style; same variable names, and I don't see the point of using this, especially after looking at the docs example. I look at this:
public Test(int a, int b) {
x = a;
y = b;
However, the use of the this keyword isn't necessary; In my code, I have a variables in my class (e.g. xCoordinate) where I don't use the this keyword (it's not static).
What I've been struggling to understand is what the difference is between non-static variables and this variables. Is there a difference? In one of my classes (the Paddle for Pong), I have this:
public class Pong {
public int xCoordinate;
public int yCoordinate;
and so on...
I never use the this keyword anywhere, and the data is stored within it's own instance.
Bottom line, my question is what is the difference between non-static variables and this.variables. Is it a standard coding practice? Why would I ever you the this keyword on non-static variables?
I think you may have almost answered your own question. You provided the function
public Test(int x, int y) {
this.x = x;
this.y = y;
}
However, what do you think would happen if you wrote it this way instead?
public Test(int x, int y) {
x = x;
y = y;
}
Noticed that I removed the this in the second function. Therefore, x and y would just be referring to the local x and y variables. this allows you to specify that you actually want to use the non-static class variables x and y.
If, as is typical, the parameter variable names of a constructor (say x) are the same as fields of the class, then the field names are shadowed by the parameters passed.
this is used in this case to disambiguate: this.x denotes the field x. It makes perfect sense. this means "reference to the current instance".
So, statements like this.x = x; are quite common.
If you still continue to dislike the Java style, and you adopt m_x-style notation for class fields, then you can write m_x = x; in your constructor. As you rightly point out, this is then not required.
this is also used as the notation for delegating constructors, as you point out.
The "this" keyword allows you to difference between method and instance variables:
public class Point {
private int x;
private int y;
public void add(int x, int y) {
this.x += x;
this.y += y;
}
}
There is no this variables. It's just used to tell the compiler that the variable you want to change is the declared field and not the local variable, in case they have the same name.
For the constructor part, this is just a shortcut for classes which have multiple constructors. You can write the code once and just call that from the alternative constructors.
There is also a similiarly used keyword super, which allows you to call methods and constructors of the superclass:
public SomeClass(int x) {
super(x);
super.someMethod(); // even if we would have overridden someMethod(),
// this will call the one from the superclass
}
Here's one instance where you would need the 'this' keyword:
public class Pong {
public int xCoordinate;
public int yCoordinate;
public Pong (int xCoordinate, int yCoordinate) {
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
}
}
So I'm having a problem with passing values to another class in java.
I have an application which accepts an equation from the user, after the button gets clicked, it finds out the number of variables the equation has and I'm putting the variables in two lists. Now, I need to pass these variables to another class.
here's the snippet of code where I need to use the variables:
beeColony.java
public class beeColony {
int D;
double Foods[][]=new double[FoodNumber][D];
public void getDimension(int D)
{
this.D = D;
}
}
based from here, I need to initialize the variable Foods into having a size depending on the FoodNumber and D. There's no problem w/ regards to the FoodNumber since it is a static one.
in my main application there is an event handler
private void getvalueMouseClicked(java.awt.event.MouseEvent evt) {
bee.getDimension(dim);
}
when I output the variable D in one of my methods, it is equal to the value that I assigned it to. My problem is that the size of array Foods. I get an IndexOutOfBounds Exception. I think that when I initialize the array Foods, it is unable to get the value of D.
Any thoughts on how to fix this?
Why are you using getDimension() to set a value?
The reason this is happening is because you must have created a new class of beeColony and while doing that you used the default value of D (set to zero). It would then use this value of D to create the Foods array. This would create a Foods array of size FoodNumber x 0
I would change it as follows:
public class beeColony {
int D;
double Foods[][]=null;
public void getDimension(int D)
{
this.D = D;
this.Foods = new double[FoodNumber][D];
}
}
}
How to call distanceTo(Point p) of Point.java into Point2.java under a method takes no parameter? There should be a way but I cannot find from my materials. Could anybody help me? It has been doing 2 days. Please help...
---------------------Point.java---------------------------------
public class Point{
private int x;
private int y;
//x and y coordinates as parameters
public Point(int x, int y){
this.x = x;
this.y = y;
}
//I want to call this method by calling a method which taken no parameter in Point2.java.
public double distanceTo(Point p){
return Math.sqrt(((x - p.x) * (x - p.x)) + ((y - p.y) * (y - p.y)));
}
}
---------------------ClonePoint.java---------------------------------
public class ClonePoint{
private int a;
private int b;
//x and y coordinates as parameters
public ClonePoint(int a, int b){
this.a = a;
this.b = b;
}
//I failed with this way. Can anybody correct me?
public double measureDistance(){//it should be takes no parameter.
return distanceTo(ClonePoint p)
}
}
----------------------PointDriver.java-----------------------------
public class PointDriver {
public static void main(String [] args) {
Point2 nn = new Point2(11, 22);
Point2 mm = new Point2(33, 44);
System.out.println(nn.distanceTo(mm)); //I succeeded with this!
System.out.println(nn.measureDistance(mm)); //But I got an error illegal start of expression
}
}
#Evan a class is a generalized container for your things. A car, a person, a point (in your case).
Everytime you want to "create" one or more object of your defined class, you instantiate them:
Person evan = new Person();
Person rob = new Person();
both of us are person, you don't really need to define class Person1 and Person2!
And in a class you should define the methods used to "relate" to other similar objects.
For example:
// In Person.java
public void greet(Person p) {
System.out.println("My name is "+this.name+". Nice to meet you +"p.getName());
}
// In main
rob.greet(evan); // it now gives compile errors of course but take the point :P
What you want to achieve is to create a better and more complete Point class with all the methods you want to use. In the end, just initialize more Point objects (same class!) in your main and play with them.
Hope it helps :)
EDIT
Ok, perhaps I've got what your homework wants you to perform.
A "parameter-less" method measureDistance() should make you wonder one important thing: "distance FROM which point????".
Obviously, if the function takes no parameters all the information needed to that calculus must be in the object which calls it. Don't you think?
So, you probably want to achieve a secondary class (if you really need to define it as Point2 it's ok, but change that name because it's confusing) which can take a Point in its constructor (saving this information in itself) and then use that Point to measure distance from it.
Example
public class Point2{
private int a;
private int b;
private Point startingPoint;
public Point2(int a, int b, Point p){
this.a = a;
this.b = b;
startingPoint = p;
}
// Computes the distance from starting point to this
public double measureDistance(){//it takes no parameter.
return startingPoint.distanceTo(a, b);
}
/*
if you can't edit distanceTo() it gets a little verbose but you must create a
Point with Point2 coordinates - remember this example when you will study Inheritance
public double measureDistance() {
Point endingPoint = new Point(a, b);
return startingPoint.distanceTo(endingPoint);
}
*/
}
First, it is not good idea to duplicate a class that does the same thing because you are doing extra unneeded work. Second, if you make various point types, you are loosing the advantage of seamless compatibility between them.
Then, if you want to call method from other class you can do it like this:
NameOfOtherClass.SomeMethod()
But you have to declare the SomeMethod in the other class as static...
public static double SomeMethod() { ... };
But then you can't use the method to access the data of your concrete points you have created in your code, so any data should be put into parameters.
If you want to do it your way, you have to just add a parameter to public double measureDistance()
function so the function has access to another point to measure distance to.
I realize that if I pass an object as a parameter of a function and do changes to it, the changes "stay" with the object. But it is not the case for an integer.
public void start() {
int x = 100;
modify(x);
// I would like x to be 200 now. But it isn't :(
}
public void modify(int y) {
y *= 2;
}
So basically, is there a way to achieve what I wanted in the code above? Is it possible to modify an integer like that (like an object reference)?
While working with primitives there is no concept of "reference". But you may achieve what you want by doing something like below:
x = modify(x); may be code want.
Now x contains the results of modify(x) method invocation.
You cannot do that. Primitives are passed by value. (References are also passed by value. You can't modify an object reference; you can only modify the object that is referenced.) The best you can do is:
public void start() {
int [] x = {100};
modify(x);
// x[0] is now 200 :)
}
public void modify(int []y) {
y[0] *= 2;
}
The array reference x is passed by value, but you can modify the array elements. Note that passing an Integer won't help, because Integer objects are immutable.
Alternatively, you can redesign your method to return the doubled value and assign it in the calling code (as Nambari suggests).
A third possibility, beside passing an array or using a return value, would be to pass an object of some ValueHolder class with a getter and setter:
public class IntValueHolder
{
private int value;
public int getValue()
{
return this.value;
}
public void setValue(final int value)
{
this.value = value;
}
}
This is technically very similar to passing an array, but is IMHO a bit cleaner, i.e. it better describes your intent.
One thing you can do is get the return value of the modify() method and assign it to the variable as follows.
public void start() {
int x = 100;
x=modify(x);
}
public int modify(int y) {
return y *= 2;
}
I need to translate some c++ into java, but I have I few issues.
How to I have to deal with pointers when they are declared as arguments in the Method?
static void test( double *output){}
Also what is and how can I replace struct?
struct test { int t;
int arg;
float *pva;
double *array;
}
And then in the code they use:
double test(struct test *test)
{}
Oh and a last one.. this is also inside struct test, what means :
test->arg
static void test( double *output){}
This needs more context, it can mean a pointer to a double or an array of doubles.
struct test { int t;
int arg;
float *pva;
double *array;
}
A struct is a class with default public access level. You can replace it with a class with public members.
test->arg
This accesses the arg member in test.
You do not have pointers in Java, only references and only for objects (not for primitive types). References are like pointers, but you use the '.' notation instead of '*' or '->'. Also, you do not need to delete objects in Java, you just stop using them and eventually the garbage collector with destroy them.
Answering your points above, from bottom to top:
If test is a pointer to a struct or class in C++, and arg is a member variable of test, then
test->arg
is used to access the member through the pointer. This would map to
test.arg
in Java, if arg is a public member variable of the test object.
I would translate the following:
struct test
{
int t;
int arg;
float *pva;
double *array;
}
...
double test(struct test *test)
{}
to
public class Test
{
public int t;
public int arg;
float [] pva;
double [] array;
}
...
public static double test(Test test)
{}
For the first case, i.e. the function
static void test( double *output){}
you cannot pass a pointer to double and modify the double in Java. You have to return a double. If you need the double also as an input parameter, you specify it as a normal parameter that is passed by value:
static double test(double output)
{}
I hope this helps.
In the simple cases you can replace float * and double * with float [] and double [] However C++ allows you to do all sorts of unpleasant things which are difficult to translate into Java because it is not allowed in Java.
You can replace a struct with a class
If you want to understand basic C++ syntax, I suggest you read a guide on how to program in C++.
(1) static void test( double *output){}
Here double* can be replaced with a Double[] (assume that you do a new Double[]) and the method can be put inside a class.
class testMethod {
public static void test (Double []output) { }
}
(2) how can I replace struct?
It can be replaced with a class.
class test {
public int t;
public int arg;
public Float []pva;
public Double []array;
}
(3) double test(struct test *test) {}
It can be,
double test (test t) {}
(4) test->arg
Java doesn't have pointers (though it's implemented with reference); so above statement will be test.arg