The Artima Developer Community
Sponsored Link

Java Answers Forum
2 dimension array of objects.how do i initialize values;

1 reply on 1 page. Most recent reply: Dec 6, 2003 4:50 PM by Kishori Sharan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
black

Posts: 1
Nickname: scorpion
Registered: Dec, 2003

2 dimension array of objects.how do i initialize values; Posted: Dec 6, 2003 1:40 PM
Reply to this message Reply
Advertisement
i 'm trying to create a 2 dimension array of objects and initialize their values.here is the code that i have written.please help...

import java.awt.Color;

public class Piece {
private Color color;

public Piece(Color aColor) { //constractor
color=aColor;
}

public class Cell {
boolean hasObstacle;
Piece piece = null;

public Cell( ) { //constractor
setObstacle(false);
}

public void setObstacle(boolean obstacle) {
hasObstacle=obstacle;
}

}


public class Board {

public Board(int size) { //constractor
Cell cell[][]=new Cell[size][size];

for (int i=0;i<size;i++)
for (int j=0;j<size;j++)
cell[j].hasObstacle=false; //???
}
}

public static void main(String args[]) {
int n=8;

Board board=new Board(n);

for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
System.out.println(board.cell[j].k);
}


Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: 2 dimension array of objects.how do i initialize values; Posted: Dec 6, 2003 4:50 PM
Reply to this message Reply
>for (int i=0;i<size;i++)
>for (int j=0;j<size;j++)
>cell[j].hasObstacle=false; //???


When you created call[][] then all elements are initailized to null. After creating the array, first thing you need to do it to create a new Cell object and assign it to each element. You can do it as:

for (int i=0;i<size;i++){
      for (int j=0;j<size;j++) {
        cell[i][j]= new Cell(); // Create and assign new Cell object
      }
}
 


Since hasObstacle is boolean instance variable for Cell object, its value will be set to false by default. So,each cell value for hasObstacle read as
cell[i][j].hasObstacle 
will be false after the above for loop is executed.

Flat View: This topic has 1 reply on 1 page
Topic: exception handling Previous Topic   Next Topic Topic: Connect 4 game

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use