我目前有一个ArrayList,它包含前1000个素数。我能够成功地将列表打印到控制台。ArrayList中不存在Java索引<Double>
我则采用以下方法:
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
指数位置,所以为什么会发生这种情况?索引位置随每次运行而改变,但每次运行时都会出现错误。
谢谢。
告诉我们在哪里是scasol声明 – smas 2011-03-22 18:50:51
值得注意的是你的'scasol.replace()'方法没有做任何事情,因为它们返回了一个你没有做任何事情的新字符串。另外,你的缩进表明你相信'scasol = x'行是else块的一部分,但它不是。这里的最佳做法是总是使用大括号,即使它们是可选的。 – dty 2011-03-22 19:08:07
@dty感谢您的评论。我明白你的意思 - 我也怀疑'scasol.replace()'方法没有做任何事情,但我不知道该怎么做。我打算做的是做一个小的改变(因此方法名)到一个'String'变量,所以当遇到'1'时,它变为'0',反之亦然。请问你会推荐什么? – MusTheDataGuy 2011-03-22 20:29:18