user4824195
user4824195

Reputation: 119

Locate coordinates of element in 2D Array

I think I must be losing it. I'm trying to locate the coordinates of an element in a 2D Array.

I've dumbed the code down to as simple as I could and still can't get it right. I'm very new to Java

Please tell me why the answer to this is always 42.0, no matter where I put the ' * '

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);
}

Upvotes: 0

Views: 2801

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520888

Look closely at this line:

star = board[i][j];

You are assigning a char to a double. The value 42 is the ASCII value of an asterisk *. If you want to print out the coordinates (which are two values, not just one), then try this:

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 + ")");
}

Upvotes: 4

shree.pat18
shree.pat18

Reputation: 21757

The ASCII value 42 corresponds to the * symbol. Your code is in effect retrieving the value * and then casting it implicitly to a number, which will always be 42. You are not going to see a difference regardless of position, because you are only looking for the '*' value and not its position or anything else.

Upvotes: 2

AkiRoss
AkiRoss

Reputation: 12273

Ahah it's kinda funny :) You find the star, and you assign the star to a double value:

star = board[i][j];

That is, you assign '*' to a double, getting the ASCII value of the * character, which is - in fact - 42.

Here's some code that shows that it's found:

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;
        }
    }
}

Upvotes: 2

Related Questions