Reputation: 109
I'm trying to do a simple code in Java : I have a class called "Bloc", which create blocks (square), which inside it I create a random width (largeur), and a random height (hauteur) between 2 ints, and I create a random number of blocks (nombreBloc). I also create an ArrayList to put every block in it, to see how much I have left.
So, I did a function called "insererBlocList" (insert the block into the ArrayList), which create "nombreBloc" (numberBloc) of blocks and put it into the ArrayList.
I've got a graphic interface, in which I have 1 panel for the windows, which inside it I have 2 other panels: One of them is to put every block I created into it.
Here is my problem, I've got a "StackOverflowError" inside my function "insererBlocList", which means there is an infinite loop, but after writing the path of code, I don't see where I did the mistake... Here is the code :
Bloc class:
public class Bloc extends JPanel{
private int hauteur, largeur, nombreBloc;
private boolean premierPassage = true;
private ArrayList<Bloc> listeBlocRestant;
private Random rand = new Random();
public Bloc() {
this.hauteur = 10 + rand.nextInt(50 - 10);
this.largeur = 10 + rand.nextInt(50 - 10);
listeBlocRestant = new ArrayList<Bloc>();
if(premierPassage == true) {
this.nombreBloc = 5 + rand.nextInt(30 - 5);
insererBlocList();
}
}
public ArrayList<Bloc> insererBlocList(){
premierPassage = false;
for(int i=0; i<nombreBloc; i++) {
Bloc bloc = new Bloc();
listeBlocRestant.add(bloc);
}
return listeBlocRestant;
}
The GUI part of the panel block:
private JPanel initPanelBloc() {
panelBloc = new Bloc();
}
Upvotes: 0
Views: 82
Reputation: 111
You might thought premierPassage = false; will prevent method calling again. But insererBlocList() makes new instance of Bloc and this boolean value will be true again. Change code like this:
public class Bloc extends JPanel{
private int hauteur, largeur, nombreBloc;
private ArrayList<Bloc> listeBlocRestant;
private Random rand = new Random();
public Bloc(boolean premierPassage) {
this.hauteur = 10 + rand.nextInt(50 - 10);
this.largeur = 10 + rand.nextInt(50 - 10);
listeBlocRestant = new ArrayList<Bloc>();
if(premierPassage == true) {
this.nombreBloc = 5 + rand.nextInt(30 - 5);
insererBlocList();
}
}
public ArrayList<Bloc> insererBlocList(){
premierPassage = false;
for(int i=0; i<nombreBloc; i++) {
Bloc bloc = new Bloc(false);
listeBlocRestant.add(bloc);
}
return listeBlocRestant;
}
And change GUI part like this:
private JPanel initPanelBloc() {
panelBloc = new Bloc(true);
}
Upvotes: 2
Reputation: 393856
Your Bloc
constructor calls insererBlocList()
, and insererBlocList()
creates additional Bloc
instances (for each of them the constructor calls insererBlocList()
), which leads to an infinite chain of method calls, leading to StackOverflowError
.
insererBlocList()
probably shouldn't be called by the Bloc
constructor.
Upvotes: 5