Hello!

It is necessary to implement a mechanism that would recreate the class BattleField, if in the class Ship the cycle was executed N times.

Please suggest the best and correct solution for this.

I expect from the program:

IF in Ship.java the loop was executed N times, THEN in GameInitialization.java to recreate an object of class BattleField and Fleet

//GameInitialization.java GameInitialization(){ BattleField humanBattleField = new BattleField(); Fleet humanFleet = new Fleet(humanBattleField); } //Fleet.java Fleet(BattleField battleField) { Ship[] fleet = new Ship[10]; this.battleField = battleField; for (int i = 0; i < fleet.length; i++) { if (0 == i) { fleet[i] = new Ship(4, i, battleField); //do actions } } } //Ship.java Ship(int shipLength, int shipNumber, BattleField battleField){ while (false == isShipPlacementCorrect) { while (false == isInitialCoordinatesCorrect) { //do actions } } } 
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky
  • It will be easier if the choice of the position of the ship takes on the class Fleet , and checking the possibility of the installation will move as a method to BattleField or to Fleet . Otherwise, the only option to inform the caller that the constructor was unable to throw an exception. But it is ugly, as well as serious work in the designer in general. It would be a little better to have a factory method that returned the ship if successful and threw an exception on failure, but still not very much. - zRrr
  • @zRrr is just that: Ship generates the coordinates in a cycle and checks whether it is possible to place itself on the field, returns true. After Fleet calls the BattleField method and places the ship on the field. Sometimes a situation happens when this Ship cycle goes almost to infinity, since it cannot find free coordinates for location. And I do not know how best to deal with this. - Maxim

1 answer 1

 Ship(int shipLength, int shipNumber, BattleField battleField){ int counter = 0; while (false == isShipPlacementCorrect) { while (false == isInitialCoordinatesCorrect) { if (counter >= N) { counter=0; // пересоздаем } counter+=1; //do actions } } } 
  • How to delete the current one from Ship and create a new BattleField? - Maxim