I currently have an ArrayList which houses the first 1000 prime numbers. I am able to successfully print the list to the console.
I am then applying the following method:
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);
}
Main method:
public static void main(String[] args){
ArrayList<Double> primes = new ArrayList<Double>();
primes.addAll(CS2004.ReadNumberFile("1000 Primes.txt"));
RMHC(primes, 10, 50);
}
ScalesSolution class:
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()
}
Whenever I call the method, however, I receive the following error no matter what I enter for the parameters. (FYI, ArrayList<Double> weights is the list of primes, int n is the size of the solution to look for and iter is the number of iterations that the algorithm will run for.)
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)
As mentioned above, the list contains 1000 elements (1000 – 1 indices), however I always receive the error above.
As you can see, it points to an error at index position 6, but there are 1000 - 1 index positions, so why does this happen? The index position changes with each run, but each and every time I run it, the error arises.
Thank you.
The problem is on this line:
The value of p (6) that you are passing in to the substring method is too large for the string scasol.