我目前有一个 ArrayList,其中包含前 1000 个素数。我能够成功地将列表打印到控制台。
然后我应用以下方法:
public static ScalesSolution RMHC(ArrayList<Double> weights, int n, int iter){
private String scasol;
ScalesSolution sol = new ScalesSolution(n);
for(int i = 1; i <= iter; i++){
double oldsol = sol.ScalesFitness(weights);
sol.smallChange(n);
sol.println();
double newsol = sol.ScalesFitness(weights);
if(newsol > oldsol){
newsol = oldsol;
}
}
return(sol);
}
主要方法:
public static void main(String[] args){
ArrayList<Double> primes = new ArrayList<Double>();
primes.addAll(CS2004.ReadNumberFile("1000 Primes.txt"));
RMHC(primes, 10, 50);
}
ScalesSolution 类:
public class ScalesSolution{
public void smallChange(int n)
{
Random rand = new Random();
int p = (rand.nextInt(n) - 1);
//Checks if p < 0. If so, then p will not have 1 subtracted from it.
if(p < 0){
p = (rand.nextInt(n));
}
String x = new String();
x = scasol.substring(0, p);
if (scasol.charAt(p) == '0')
scasol.replace('0', '1');
else if (scasol.charAt(p) == '1')
scasol.replace('1', '0');
scasol = x;
}//End smallChange()
}
但是,每当我调用该方法时,无论我输入什么参数,我都会收到以下错误。 (仅供引用,ArrayList<Double> weights
是素数列表,int n
是要查找的解决方案的大小,iter
是算法将运行的迭代次数。)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.substring(Unknown Source)
at ScalesSolution.smallChange(ScalesSolution.java:90)
at Lab8.RMHC(Lab8.java:15)
at Lab8.main(Lab8.java:46)
如上所述,列表包含 1000 个元素(1000 - 1 个索引),但是我总是收到上述错误。
可以看到,它指向索引位置6处的错误,但是有1000 - 1
指数持仓,那么为什么会出现这种情况呢?索引位置随着每次运行而变化,但每次运行时都会出现错误。
谢谢。
最佳答案
问题出在这一行:
x = scasol.substring(0, p);
您传递给 substring 方法的 p (6) 值对于字符串 scasol 来说太大。
关于Java ArrayList<Double> 中不存在索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5396285/