下面的代码应该返回多维数组中一个项的索引值。然而,当我运行它时,它会返回给我这个:
Found at: [I@7ea987ac
public static String findWord(char[][]board, String word) {
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (board[row][col] == word.charAt(0)) {
return "Found at: " + new int[] {row,col};
}
}
}
return "Not found.";
}
代码没有给我返回正确的索引值,这是怎么回事?
您将以字符串的形式返回一个数组,因此您将获得该数组返回的默认toString()
,即[I@7ea987ac
,其中[I
表示int数组,数字是数组的hashCode。
解决方案:不要将数组作为字符串返回,而是提取所需的字符串数据并返回。
相反,返回类似以下内容:
return String.format("Found at [%d, %d]", row, col);
您从数组中获得默认的toString()
,您可以更改此
return "Found at: " + new int[] {row,col};
将Arrays.toString(int[])
与一起使用
return "Found at: " + Arrays.toString(new int[] {row,col});