Reputation: 815
I'm trying to populate an object array with new objects. Here is the code:
Main class
public class Bejeweled extends JFrame{
public Bejeweled(){
Board board = new Board();
getContentPane().add(board);
board.start();
}
public static void main(String[] args){
Bejeweled game = new Bejeweled();
}
Board class
public class Board extends JPanel{
final int BOARDHEIGHT = 8;
final int BOARDWIDTH = 8;
Gem[] gems;
public Board(){
gems = new Gem[BOARDHEIGHT * BOARDWIDTH];
}
public void start(){
fillBoard();
}
public void fillBoard(){
Arrays.fill(gems, new Gem());
for(Gem gem : gems){
System.out.println(gem.type); //**This was expected to print random numbers**
}
}
}
Gem class
public class Gem {
public int type;
public Gem(){
this.type = genType();
}
public int genType(){
return (int) (Math.random() * 7);
}
}
The problem is that all objects appear to be the same. I know I should encapsulate type in the Gem class, but I'm trying to limit the amount of code I'm posting here.
A new Board gets created from the main class, in the Board class a Gem[] is filled with newly created Gems (class Gem).
Upvotes: 0
Views: 616
Reputation: 77187
Arrays.fill
fills the array with the value you provide, which in this case is a particular instance of Gem
. Instead, you need to use a for
loop and set each of the array elements to a distinct Gem
:
for(int i = 0; i < gems.length; i++) {
gems[i] = new Gem();
}
Note that if you really have an 8x8 board, it's much preferable to have a Gem[8][8]
than a Gem[8*8]
.
Upvotes: 2