Reputation: 200
I dont understand why this is happening. without the print statement the code works fine but when i try to print the elements i get ArrayIndexoutOfBounds. For example if i try to feed 3 elements i get exception thrown. can anyone please explain
class MyClass
{
int search(OtherClass obs,target) {
double a[]=new double[obs.length];
for(int i=0;i<obs.length;i++)
{
a=obs[i].getTarget();
System.out.println(a[i]);//without this it does not throw
}
}
}
class OtherClass
{
String Target;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
}
Upvotes: 0
Views: 73
Reputation: 1596
You should use this, this statement will set value from obs[i].getTarget()
to a[i]
a[i]=obs[i].getTarget();
Edited:
If getTarget()
method returns an array then you can this way,
for(int i=0;i<obs.length;i++)
{
double a[] =obs[i].getTarget(); // putting the array from getTarget() to a[]
for(int j=0;j<a.length;j++)
System.out.println(a[j]);//printing all the values of a[]
}
Upvotes: 0
Reputation: 10263
In your code obs
is an array: obs[i]
; each position of that array is, itself, other array: obs[i].getTarget() #=> double[]
I guess if, really obs
has a method named getTarget()
which returns an array.... probably this?
double a[] = new double[obs.length];
double obsArray[] = obs.getTarget();
for(int i=0; i<obs.length; i++){
a[i] = obs[i];
System.out.println(a[i]);
}
Upvotes: 0