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).
Arrays.fill(gems, new Gem());. In this line you create a single gem, and use the same gem to fill the array. Have you considered using a for loop instead?Arrays.setAll.