Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Java coding question?

I am working on writing a text based game program, and am stuck at a few of the logistics. It's pretty clear that the jump in level as far as what I need to understand about java from the last class I took to this one is huge. Some of these things, I simply can't imagine what to do with them.

I am breaking the assignment down into pieces to make them more manageable.

I am at a point in the game where players need to put a piece onto a gameboard which I have created using ascii art and a 2D array. I put numbers into each of the array slots to begin the game to make space selection more intuitive for the user.

It should look like this, or similar, to give you an idea:

| 1 | 2 | 3 | 4 |

| 5 | 6 | 7 | 8 |

| 9 | 10 | 11 | 12 |

| 13 | 14 | 15 | 16 |

The formatting will be better, but you get the idea.

What I am confused about is how to do a check to make sure that the user selects a location that doesn't already have a piece placed on it. If it doesn't, the number gets replaced by a letter representing their name. If it does, they get and error and are told to place again.

How to I check to make sure there isn't a C, or J or whatever, and if there is, to repeat the prompt and check until they enter something valid?

I hope this makes sense lol.

Here is sort of what I have so far. I am using notepad so there may be bugs I have to fix, but I want general form right now.

// method to place a piece for player1

public static placePiece(int [][] gameBoard)

System.out.println( Player1Name + ", please place your piece by choosing a board location");

int addPiece = console.nextInt;

if(addPiece > boardSize*boardSize || addPiece < 1)

{

System.out.println("That is not a valid choice. Please choose an unoccupied space on the game board");

}

else??

{

}

1 Answer

Relevance
  • McFate
    Lv 7
    10 years ago
    Favorite Answer

    What is the contents of your array gameBoard? Let's say that gameBoard[i][j] is 0 if the cell is unoccupied, and 1 if it contains a piece by player 1, and 2 if it contains a piece by player 2. Then you would write something like:

    int addPiece = console.nextInt();

    int row = (addPiece - 1) / boardSize;

    int col = (addPiece - 1) % boardSize;

    [your existing if-statement]

    else if ( gameBoard[row][col] != 0) {

    System.out.println("That square is occupied");

    } else {

    gameBoard[row][col] = 1; // Player 1

    }

Still have questions? Get your answers by asking now.