[英]Locate coordinates of element in 2D Array
我想我一定會失去它。 我正在嘗試在2D數組中定位元素的坐標。
我已將代碼精簡到我可以做到的最簡單的程度,但仍然無法正確完成。 我對Java很陌生
請告訴我,無論我在何處放置“ *”,為什么答案總是42.0
public static void main(String[] args) {
locateStar(board);
}
static char[][] board = {
{ '.', '.', '.', '.' },
{ '.', '.', '.', '.' },
{ '.', '.', '.', '*' },
{ '.', '.', '.', '.' }
};
public static void locateStar(char[][] board) {
double star = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '*') {
star = board[i][j];
}
}
}
System.out.println(star);
}
仔細觀察這一行:
star = board[i][j];
您正在將char
分配給double
。 值42
是星號*
的ASCII值。 如果要打印出坐標 (兩個值,而不僅僅是一個值),請嘗試以下操作:
public static void locateStar(char[][] board) {
int x, y;
for (int i=0; i < board.length; i++) {
for (int j=0; j < board[0].length; j++) {
if (board[i][j] == '*') {
x = i;
y = j;
}
}
}
System.out.println("Found a star at (" + x + ", " + y + ")");
}
嗯,這有點好笑:)找到星星,然后將星星賦給double值:
star = board[i][j];
也就是說,將'*'
分配給雙精度字符,得到*字符的ASCII值,實際上是42。
這是一些代碼,表明已找到它:
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '*') {
System.out.println("Found at " + i + " " + j);
break;
}
}
}
ASCII值42對應於*符號。 您的代碼實際上是檢索值*,然后將其隱式轉換為始終為42的數字。無論位置如何,您都不會看到差異,因為您只是在尋找'*'值而不是其值位置或其他任何東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.