这里有4x4个字符的数组,我需要获得数组边缘的字符的公共值。。。我尝试了其他与我的问题类似的问题的解决方案,但我仍然得到了同样的错误。,
这是我的代码。。
//arr2[][]
// arr2[3][0] = 'H';
// arr2[3][1] = 'E';
// arr2[3][2] = 'L';
// arr2[3][3] = 'P';
//arr3[][]
// arr3[1][3] = 'T';
// arr3[2][3] = 'O';
// arr3[3][3] = 'P';
//I specifically need the get the 'P' at [3][3]..
for(o = 0;o<count;o++){
char letter = out.charAt(o);
for(int m = 0; m < 4; m ++){
for(int n = 0; n < 4; n ++){
if(Arrays.asList(arr3[m][n]).contains(letter)){
r = m;
c = n;
}
}
}
right = arr2[r][c+1];
left = arr2[r][c-1];
up = arr2[r-1][c];
down = arr2[r+1][c];
if(o==0){
if(c==0){
if(r==0||r==3){
if(right!=null){
l = right;
}
}else{
if(right!=null){
l = right;
}else if(up!=null){
l = up;
}
}
}else if(c==3){
if(r==0||r==3){
if(left!=null){
l = left;
}
}else{
if(left!=null){
l = left;
}else if(up!=null){
l = up;
}
}
}else{
if(r==0||r==3){
if(left!=null){
l = left;
}else if(right!=null){
l = right;
}
}else{
if(left!=null){
l = left;
}else if(right!=null){
l = right;
}else if(up!=null){
l = up;
}
}
}
}
}else if(o==(count-1)){
if(vertical == 1){
if(c==0){
if(r==0||r==3){
if(right!=null){
l = right;
}
}else{
if(right!=null){
l = right;
}else if(down!=null){
l = down;
}
}
}else if(c==3){
if(r==0||r==3){
if(left!=null){
l = left;
}
}else{
if(left!=null){
l = left;
}else if(down!=null){
l = down;
}
}
}else{
if(r==0||r==3){
if(left!=null){
l = left;
}else if(right!=null){
l = right;
}
}else{
if(left!=null){
l = left;
}else if(right!=null){
l = right;
}else if(down!=null){
l = down;
}
}
}
}
}else{
if(vertical == 1){
if(c==0){
if(right!=null){
l = right;
}
}else if(c==3){
if(left!=null){
l = left;
}
}else{
if(right!=null){
l = right;
}else if(left!=null){
l = left;
}
}
}
}
k = Character.toString(letter);
letr = Character.toString(l);
在您的代码中,
for(int m = 0; m < 4; m ++){
for(int n = 0; n < 4; n ++){
if(Arrays.asList(arr3[m][n]).contains(letter)){
r = m;
c = n;
}
}
}
在这里,你分配r和c,在某种情况下可能是0
或3
,然后你下面的代码,
right = arr2[r][c+1];
left = arr2[r][c-1];
up = arr2[r-1][c];
down = arr2[r+1][c];
在上面的赋值中,您有c + 1
、r + 1
、c - 1
、r - 1
,如果上一个循环将r和c赋值为0或3,则这些值肯定会超出界限。
你能运行这个并告诉我们它是否有帮助吗?
char[][] arr2 = ... // your array
char[][] arr3 = ... // your other array
// inspect all common indeces:
for (int i = 0; i < arr2.length && i < arr3.length; i++) {
for (int j = 0; j < arr2[i].length && j < arr3[i].length; j++) {
// print value, if value is the same:
if (arr2[i][j] == arr3[i][j]) {
// here you know that two characters on the same index are the same.
// you have the information about the character and the indeces:
System.out.println("Found common value at index (i,j)->"
+ "(" + i + "," + j + "), char '" + arr2[i][j] + "'");
}
}
}
使用一个类似于您评论的示例中的数组,这将给出以下输出:
Found common value at index (i,j)->(3,3), char 'P'
这似乎就是你想要的。假设两个数组具有相同的维度,此解决方案将查看两个数组中的每个索引。如果一个数组比另一个大,那么只会查看常见的索引。你提到了数组的边缘。我不清楚,如果你的意思是只有边或包括边
感谢那些帮助我解决这个问题的人。。我能够使用模得到数组边缘的值。。我能够阻止出界。。。https://stackoverflow.com/a/12743834/2078012这个来自另一个问题的链接回答了我的问题。。再次感谢…:-)