在Java中,当这两个值相等时,为什么会出现交换错误?
我不知道为什么会出现这个错误,也不知道如何解决它。我收到一个运行时异常:在Java中,当这两个值相等时,为什么会出现交换错误?,java,swap,Java,Swap,我不知道为什么会出现这个错误,也不知道如何解决它。我收到一个运行时异常: for(int j = 0; j < instances[maxInstance].length; j++){ centroids[orphanCentroid][j]=instances[maxInstance][j]; } for(int j = 0;
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 ;
}
它发生在这条线上:
double temp = centroids[maxInstance][j] ;
我想你需要
for(int j = 0; j < centroids[maxInstance].length; j++){
}
for(int j=0;j
在你的第二个for循环中。这两种方式都可以,如果没有额外的信息,我真的无法判断哪一种是超出范围的 案例1:质心.length
instances[10];
centroids[5];
int maxInstance = 5;
new instances[maxInstance][10];
new centroids[maxInstance][5];
潜在解决方案:检查instances.length的大小,并确保
centroids.length是centroids[maxInstance]
和instances[maxInstance]
相同的长度?在您的问题中,第二个for循环之后的额外的花括号是打字错误吗?或者你有一个匿名区块吗?@是的,问题在于这个!我想只有当质心[maxInstance]
比实例[maxInstance]
短时,才会发生这种情况。因此,也许您可以将代码发布到实际设置这两个数组的位置。问题不在您发布的代码片段中。假设您的双开括号是一个输入错误
new instances[maxInstance][10];
new centroids[maxInstance][5];
j=5;
centroids[maxInstance][5]
for(int j = 0; j < centroids[maxInstance].length; j++){ //replace with centroids