【问题标题】:Array index out of bounds - 2d to 1d数组索引超出范围 - 2d 到 1d
【发布时间】:2014-12-06 05:02:17
【问题描述】:

我正在使用普林斯顿大学提出的 algs4 8-puzzle 程序。在我的第二个 for 循环中,我得到了一个数组索引越界异常。有没有人看到引发此异常的问题?我的板子类+相关方法是这样的:

public class Board {
 private final int[][] blocks;
 private final int N;

 // construct a board from an N-by-N array of blocks
 // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks){
     N = blocks.length;
     this.blocks = new int[N][];
     for (int i=0; i<N; i++){
      this.blocks[i] = Arrays.copyOf(blocks[i], N);
     }
    }

    // board dimension N
    public int dimension(){
     return this.N;
    }

   //is the board solvable? 
   public boolean isSolvable(){
      int inversions = 0; 
      List<Integer> convert = new ArrayList<>(); // convert 2d to 1d 
      for (int i = 0; i < blocks.length; i++){
          for (int j = 0; j < blocks[i].length; j++){
              convert.add(blocks[i][j]);
          }
      }
      for (int i = 0; i < blocks.length; i++){ //counts the number of inversions 
          if (convert.get(i) < convert.get(i-1)){ //ARRAYINDEXOUTOFBOUNDS -1
              inversions++; 
          }
      }
      if (inversions % 2 == 0){
          return true; //even 
      }
      return false; //odd 
  }

【问题讨论】:

  • 那么当i = 0 时,convert.get(i-1) 中的i - 1 是什么?

标签: java arrays


【解决方案1】:

convert.get(i-1) 在 i==0 时超出范围。

您可能应该更改循环的开始索引:

  for (int i = 1; i < blocks.length; i++){ //counts the number of inversions 
      if (convert.get(i) < convert.get(i-1)){ 
          inversions++; 
      }
  }

【讨论】:

  • 它试图找到不能存在于任何数组/列表/字符串中的索引-1。
猜你喜欢
  • 2014-12-03
  • 2017-07-30
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多