Reputation: 38155
I am not sure why I get this error and do not know how to solve it. I am getting a Runtime Exception:
for(int j = 0; j < instances[maxInstance].length; j++){
centroids[orphanCentroid][j]=instances[maxInstance][j];
}
for(int j = 0; j < instances[maxInstance].length; j++){
{
double temp = centroids[maxInstance][j] ;
centroids[maxInstance][j] = centroids[orphanCentroid][j] ;
centroids[orphanCentroid][j] = temp ;
}
Error is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at kmeans.KMeans.cluster(KMeans.java:75)
at kmeans.HW1.main(HW1.java:36)
And it happens at this line:
double temp = centroids[maxInstance][j] ;
Upvotes: 0
Views: 60
Reputation: 525
This can go either way, without additional information I can't really tell which one is out of bounds.
In that case you simply can't access centroids[maxInstance]
, If you define them as
instances[10];
centroids[5];
int maxInstance = 5;
Potential solution: Check the size of instances.length and make sure centroids.length <= instances.length
j
is out of boundsAssuming centroids.length <= instances.length
is true. Then
you need to check whether instances[maxInstance].length > centroids[maxInstance].length
Imaging where you define them as
new instances[maxInstance][10];
new centroids[maxInstance][5];
Then you will get java.lang.ArrayIndexOutOfBoundsException: 5
when you try to access
j=5;
centroids[maxInstance][5]
Potential solution:
for(int j = 0; j < centroids[maxInstance].length; j++){ //replace with centroids
Upvotes: 0
Reputation: 4273
I think you need
for(int j = 0; j < centroids[maxInstance].length; j++){
}
on your second for loop.
Upvotes: 2