# Learning - 2D array and method question.

Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last
• 08-31-2009, 01:29 AM
Russo
Learning - 2D array and method question.
Hi Im new to Java and enjoying it so far. I have come to my first complex bit of code and am having some trouble understanding how methods work within a class. Below is my code thus far (and detailed description of what each method is to do), it is to based around creating a GoMoku game with a 2D array. The one I am looking at is the method stone, has this been done right? Also should I use a different variable for the method board int row, col? Thanks in advance.

Code:

```import java.util.List; import java.util.LinkedList; import java.util.Collections; /**  * Board class is Public  *  * @russo  * @1.0  */ public class Board {         public final int SIZE = 15;  // number of lines in board         public final int BLACK =  1;         public final int NONE  =  0;         public final int WHITE = -1;         private int[][] board;     /* Creates a new, empty, SIZE*SIZE board */     public Board () {     //Declare Variables (ArrayRow, ArrayColumn)     int row, col;     //Create board based on SIZE     board = new int[SIZE][SIZE];     //- Initialization (set all to variable NONE 0)     for (row = 0; row < board.length; row++)     for (col = 0; col < board[row].length; col++)     board[row][col] = NONE;     }     /*     * Returns whether (row, col) is a valid board position,     * for 0 <= row, col < SIZE.     */     public boolean valid (int row, int col, boolean valid) {         //Declare variable - assume true             valid = true;         //Is the value a less than or equal to the board size? Return State             if (row < SIZE && row >= 0 && col < SIZE && col >= 0){             valid = true;             }             else                 valid = false;         return valid;     }     /* Returns whether position (row, col) is occupied, for 0 <= row, col < SIZE. */     public boolean occupied (int row, int col, boolean occupied) {         occupied = false;         if(board[row][col] != NONE){           occupied = true;}           else{             occupied = false;           }         return occupied;     }     /* Returns colour of stone at (row, col), for 0 <= row, col < SIZE */     public int stone (int row, int col, int value) {         // Implement this method.         if (occupied(row, col, true)){         value = board[col][row];         }         return value;     }     /* Clears the board */     public void clear () {       // Implement this method.     }     /* Places n random stones of given colour on the board, for n >= 0 */     public void addStones (int n, int colour) {                 // Implement this method.     }     /*     * Place 1 stone of given colour at position (row, col),     * for valid (row, col).     */     public void addStone(int row, int col, int colour) {         // Implement this method.     }     /* Removes stone from position (row, col) for valid (row, col) */     public void removeStone(int row, int col) {               // Implement this method.     }     /* Prints board, with column and row headings */     public void print () {               // Display array         Board ();         for (row = 0; row < board.length; row++)         {         for (col = 0; col < board[row].length; col++)         System.out.print(" " + board[row][col]);         System.out.println();         }     }     /*     * Returns greatest length of any line through (row, col)     */     public int maxLength (int row, int col) {                   // Implement this method.     }     /**     * Reads n >= 1, places n black stones and n white stones on the board,     * then reads a sequence of board positions, and displays the length of     * the longest line of stones of the same colour through that position.     */     private void doit () {                 // Implement this method.     }     /* Creates the app and calls doit() */     public static void main (String[] args) {         // Implement this method.   }     /**     * Returns list of 5 or more stones through (row, col)     * This method is used by the GUI version of Go Moku for     * implementing the undo functionality.     *     * DO NOT MODIFY THIS METHOD     *     * @param row        an int representing the row position     * @param col        an int representing the column position     * @return                a list of Move objects.     */     public List<Move> line (int row, int col) {         List<Move> seq = line1 (row, col, +1, +1); // down-right         if (seq.size() >= 5)             return seq;         seq = line1 (row, col, +1, 0);      // down         if (seq.size() >= 5)             return seq;         seq = line1 (row, col, +1, -1);      // down-left         if (seq.size() >= 5)             return seq;         seq = line1 (row, col, 0, -1);      // left         if (seq.size() >= 5)             return seq;         return null;     }     /**     * Returns greatest length of line through (row,col)     * in general direction (rowInc,colInc)     *     * DO NOT MODIFY THIS METHOD     *     * @param row                an int representing the row position     * @param col                an int representing the column position     * @param rowInc        an int representing a row direction indicator (-1, 0, +1)     * @param colInc        an int representing a column direction indicator (-1, 0, +1)     * @return                        a list of Move objects.     */     private List<Move> line1 (int row, int col, int rowInc, int colInc) {         List<Move> seq1 = line2 (row, col, rowInc, colInc);         List<Move> seq2 = line2 (row, col, -rowInc, -colInc);                 Collections.reverse(seq1);                 seq2.remove(0);                 seq1.addAll(seq2);                 return seq1;     }     /**     * Returns greatest length of line through (row, col)     * in direction (rowInc,colInc)     *     * DO NOT MODIFY THIS METHOD     *     * @param row                an int representing the row position     * @param col                an int representing the column position     * @param rowInc        an int representing a row direction indicator (-1, 0, +1)     * @param colInc        an int representing a column direction indicator (-1, 0, +1)     * @return                        a list of Move objects.     */     private List<Move> line2 (int row, int col, int rowInc, int colInc) {         List<Move> seq = new LinkedList<Move>();         int colour = board[row][col];         seq.add(new Move(row, col));         row += rowInc;         col += colInc;         while (valid(row, col) && board[row][col] == colour) {             seq.add(new Move(row, col));             row += rowInc;             col += colInc;         }         return seq;     } } // end Board```

· public Board() – creates a new SIZE x SIZE board array, and set all elements in board to
NONE.
· public boolean valid(int row, int col) - Returns true if row, col is a valid board
position, otherwise false. row, col is a valid position if 0 <= row < SIZE and 0 <= col < SIZE.
· public boolean occupied(int row, int col) - Returns true if the value in position
row, col of board is not NONE. Precondition: row, col is a valid board position.
· public int stone(int row, int col) – Returns the value stored in position row, col of
board. Precondition: row, col is a valid board position.
· public void clear() – Sets all elements in board to NONE.
· public void addStones(int n, int colour) – Place n stones of the given colour in
random positions on the board. Precondition: n >= 0, and colour is either 1 or -1.
The following pseudocode describes how to place n random stones of the same colour col on the
board:
Set all positions in the board to be vacant;
while (n > 0)
Let r be a random integer in the range 0 to 14;
Let c be a random integer in the range 0 to 14;
if ((r,c) is a possible board position and
position (r, c) is vacant)
Place a stone of colour col at position (r, c);
Decrement n;
To generate a random integer in the range 0 to m, simply evaluate the expression
(int)(Math.random()*m).
· public void addStone(int row, int col, int colour) - Place 1 stone of given
colour at position row, col of board. Precondition: row, col is a valid board position.
· public void removeStone(int row, int col) – Removes a stone from position row,
col of board. Precondition: row, col is a valid board position.
· public void print() - Prints board, with column and row headings (as shown above in the
sample output).
· public int maxLength(int row, int col) – Returns the greatest length of any line of
adjacent stones of the same colour through row, col. Precondition: row, col is a valid board
position.
The following pseudocode describes how to compute the length of the longest line through a given
position in a given direction. Lines may go in each of eight directions by incrementing two
parameters rinc and cinc appropriately. E.g, setting rinc to -1 and cinc to 0 generates a
vertical line upwards.
int length (int row, int col, int rinc, int cinc) {
int colour = board[row][col];
if (colour represents an empty position) return 0;
int len = 1;
row += rinc; col += cinc;
while ((row,col) is on the board and board[row][col] == colour)
{
len++;
row += rinc; col += cinc;
}
return len;
}
To compute the actual length of the longest line through a given point in a given direction it is
necessary to look both "backwards" and "forwards", and evaluate something like
length(row,col,rinc,cinc) + length(row,col,-rinc,-cinc) - 1 (but note that lengths must always be
nonnegative).
· private void doit() – Provides console based user interface and call on the methods above
to fulfil all the requirements (generate random tokens, print board, print the longest line through a
position etc.) this Go Moku project.
· public static void main(String[] args) – Creates a new Board object, and call
doit()to start the application.
• 08-31-2009, 08:07 AM
DarrylBurke
• 08-31-2009, 01:51 PM
Fubarable
Thread moved. Thanks, Darryl.
• 09-06-2009, 05:50 AM
Russo
Hi Thanks for your response. I found out the answer I needed.

In regard to this 2D array, how is it possible to print row and column headings on the 2D Array. The commented code is how I thought it could be done but obviously not. Is it to be done in the loop? Thanks in advance!

Starting from 0 to the end of the array size. eg.

Code:

```     int SIZE = 6;  // number of lines in board     int[][] board = new int [SIZE][SIZE];     int row = 0;     int col = 0;       //- Initialisation of the array     for (row = 0; row < board.length; row++)     for (col = 0; col < board[row].length; col++)     board[row][col] = 3;         //int hdrow = 0;         //int hdcol = 0;         //Print the 2D Array         for (row = 0; row < board.length; row++)         //System.out.print(hdrow++ + " ");         {             for (col = 0; col < board[row].length ; col++)             //System.out.print(hdcol++ + " ");                        System.out.print(board[row][col] + " ");                         System.out.println();         }```
• 09-06-2009, 09:18 AM
DiamondDog
You could maybe do it like this?
Code:

```                int SIZE = 6; // number of lines in board                 int[][] board = new int[SIZE][SIZE];                 // Initialisation of the array                 for (int row = 0; row < board.length; row++) {                         for (int col = 0; col < board[row].length; col++) {                                 board[row][col] = 3;                         } // end for                 } // end for                 // Print the 2D Array                 // print the column headers first                 System.out.print("  ");                 for (int column = 0; column < board.length; column++) {                         System.out.print(column + " ");                 }                 System.out.println();                 // now print the array contents, with row header at the start of each                 // row                 for (int row = 0; row < board.length; row++) {                         System.out.print(row + " "); // row header at the start of the row                         for (int col = 0; col < board[row].length; col++) {                                 System.out.print(board[row][col] + " ");                         } // end for                         System.out.println();                 } // end for output:   0 1 2 3 4 5 0 3 3 3 3 3 3 1 3 3 3 3 3 3 2 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3 3 3 3 3 3 5 3 3 3 3 3 3```
• 09-06-2009, 09:37 AM
Russo
I want your brain!

That makes perfect sense and works likes a charm. Just to make sure I understand that code.

column: Use a for loop to print the column variable until it reaches the length of the board

row: For each row being printed add the row no. at the beginning then print the array in the second for loop.
• 09-06-2009, 09:49 AM
DiamondDog
Yep, that's exactly how it works.

I'm a noob too, and like you I'm enjoying learning Java.

It's cool to find a question I actually have a chance of answering. :)

Good Luck with your study of Java.
• 09-06-2009, 10:11 AM
Russo
:) Glad I could put it out there.

I've almost finished this task, just got to put my methods together and work out the kinks.

Thanks again for the help.
• 09-06-2009, 04:31 PM
Good start Russo -- Theres nothing like that moment when your code works the way you planned for the first time. Keep it up! :D
• 09-06-2009, 08:15 PM
dlorde
You have a redundant boolean parameter to your 'occupied' method.
• 09-06-2009, 11:44 PM
Russo

Yeh noticed that, same as with my valid method. Corrected it already :)

Code:

```     public boolean valid (int row, int col) {               //Is the value a less than or equal to the board size? Return State             if (row < SIZE && row >= 0 && col < SIZE && col >= 0){             return true;             }             else             return false;     }     public boolean occupied (int row, int col) {         // If the board position does not contain NONE(0) then true         if(board[row][col] != NONE){           return true;}           else{             return false;           }     }```
• 09-07-2009, 11:34 AM
Russo
How is it possible to call a method from a private void method to the main static void method?

Code:

```    private void doit () {     // Implement this method.     //generate random tokens, print board, print the longest line through a position etc.           Board();     print();     clear();  //code to be finished     }       /* Creates the app and calls doit() */     public static void main (String[] args) {         // Implement this method.     new Board.doit();  //does not work. Class is called Board }```
• 09-07-2009, 12:15 PM
r035198x
Code:

`new Board().doit();`
• 09-07-2009, 02:53 PM
r035198x is right and yes otherwise your code is fine.
• 09-10-2009, 12:37 PM
Russo
Thanks for everyones help so far!

Almost getting there with this finally. I am getting an annoying error where I cannot find where I have gone wrong..

I am splitting the value of a string. Code works if I exclude the first part of this method

Code:

``` Method doit() //First Part     // User input for value n     Scanner console = new Scanner(System.in);     System.out.print("Enter the number of tokens for each side:");     int n = console.nextInt(); // read an Integer         //Create the board //Array is initiliased all values are 0     Board();     //Add n Stones for Black and White. Adds values at random board locations     addStones(n, BLACK);     addStones(n, WHITE);     //Print the Board from the above info     print(); //Second Part (error) //error occurs on int row = Integer.valueOf(token[0]); // and int col = Integer.valueOf(token[1]); System.out.print("Enter board position (row col) : "); String input = console.nextLine(); //get the input and split value String[] token = input.split(" "); int row = Integer.valueOf(token[0]); int col = Integer.valueOf(token[1]); System.out.println(row + "," + col);```
The error I am getting is this Exception in thread "main" java.lang.NumberFormatException: For input string: ""

Method main calls another method called doit() in class Board() Thanks above as well..missed 2 brackets :p

Code:

```    /* Creates the app and calls doit() */     public static void main (String[] args)     {         // Call the doit Method         new Board().doit();     }// End Method```
The code on itself I know works ok. Only for some reason when I put it into my whole project it throws the error. Sorry I don't want to paste all my code up here as it is for an assignment and I do not want someone to come along and steal my work for the same subject (call me paranoid but its happened to me before). PM me I will be more than happy to send the code.

• 09-10-2009, 12:42 PM
r035198x
That means that there is an empty string,"", in the array. Trying to convert that to an int fails because "" is not convertible to an integer.
• 09-10-2009, 12:47 PM
Russo
any reason why the string is not getting a value? When I run it it wont even allow me to put an input in...
• 09-10-2009, 12:50 PM
r035198x
Quote:

Originally Posted by Russo
any reason why the string is not getting a value? ..

Where is the value supposed to be filed from?
Quote:

Originally Posted by Russo
When I run it it wont even allow me to put an input in...

Is it supposed to allow you to put something in then?
• 09-10-2009, 12:56 PM
Russo
I would have thought that this line will let me type the input in.

Code:

`String input = console.nextLine();`
Then it is processed with this code. where the space is the split and row becomes [0] and col becomes [1]
Code:

```String[] token = input.split(" "); int row = Integer.valueOf(token[0]); int col = Integer.valueOf(token[1]);```
Do I have to initialise another scanner class?
• 09-10-2009, 01:08 PM
r035198x
Quote:

Originally Posted by Russo
I would have thought that this line will let me type the input in.

Code:

`String input = console.nextLine();`
...

It does for me in a small test case for that part only. Better sprinkle some System.out.println statements to make sure the code does reach that line at all.
System.out.println statements are also very handly for verifying values in code.
Show 40 post(s) from this thread on one page
Page 1 of 2 12 Last