Transposing Values in Java 2D ArrayList

泄露秘密 提交于 2019-12-24 09:41:50

问题


Good evening all,

I'm trying to write a method that creates and returns a 2D array whose elements in each location are the same as the elements in the mirror image location of the parameter array. Unfortunately, no matter what pair of numbers I enter into the method call I get an "out of bounds" error in my compiler. Below is my program. Tell me where I've gone wrong! Thanks!

public static int[][] transpose(int [][] a) {
int r = a.length;
int c = a[r].length;
int [][] t = new int[c][r];
  for(int i = 0; i < r; ++i) {
     for(int j = 0; j < c; ++j) {
   t[j][i] = a[i][j];
   }
  }
return t;
 }
}

回答1:


Arrays in java are 0 based, change your assignment to c to :

int c = a[r - 1].length;



回答2:


@Suraj is correct, however you must assume the 2D array is rectangular, in which case it is sightly more efficient to change line 3 to:

int c = a[0].length;

@Kris answer text is correct however code sample is wrong line.

Note this error is a reproduction of a broken "answer" posted in "Yahoo Answers": http://answers.yahoo.com/question/index?qid=20080121204551AAn62RO




回答3:


Your problem lies in line two: a[r].length returns the number of columns, but arrays are indexed from 0. You should adjust accordingly:

int r = a.length - 1;


来源:https://stackoverflow.com/questions/5190419/transposing-values-in-java-2d-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!