如何解决java.lang.IndexOutOfBoundsException问题:索引:0,大小:0

时间:2019-07-06 04:02:44

标签: java artificial-intelligence

我正在尝试设置一个新位置,这是该算法的全局解决方案。我从名为(hh)的文本文件中读取了新位置,但是当我尝试通过代码行p.setNeighborhoodPosition(f,val1);将其传递时,出现以下错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.set(ArrayList.java:426)
    at PSOFS.Particle.setNeighborhoodPosition(Particle.java:177)
    at PSOFS.Main.main(Main.java:213)

这是我使用的代码

     Particle p = new Particle();
          if (s.getProblem().isBetter(newFitness, oldFitness)) {
              p.setNeighborhoodFitness(newFitness);
 String sc1 = new Scanner( new File("hh.txt") ).useDelimiter("\\A").next();
             sc1 = sc1.replaceAll("\\[","").replaceAll("\\]","");
            String[] doublesAsStrings1 = sc1.split(", ");
           double [] num=new double[doublesAsStrings1.length];
          for( int f = 0; f < doublesAsStrings1.length; f++ ){
              num[f] = Double.parseDouble(doublesAsStrings1[f]);
                  p.setNeighborhoodPosition(f,num[f]);}

引起错误的两行是

public void setNeighborhoodPosition(int index, double value) {
        this._neighborhood_position.set(index, value);
    }

         p.setNeighborhoodPosition(f,num[f]);

谢谢

1 个答案:

答案 0 :(得分:0)

AndreasStephen C的注释中所述,请使用类java.util.ArrayList的方法add(),例如

public void setNeighborhoodPosition(double value) {
    this._neighborhood_position.add(value);
}