[Solved] How to handle symbol not found compile error in java? [closed]


Declare a BattleShip ship1 = null variable at the top of your method and use it:

public static int plantNavy(BattleBoard myBattle, int counter) {
   BattleShip ship1 = null;

Do not re-declare the variable in your if blocks, just assign to it. i.e., do

if (counter == 0) { 
   ship1 = new LargeShip(false); 
} 

not

if (counter == 0) { 
   BattleShip ship1 = new LargeShip(false);  // note the difference!
} 

Later on you can check if it’s null to see if the ship1 has been created.

if (ship1 == null) {
   // then no ship1 has been created yet.
}

Edit
You state in comment:

@HovercraftFullOfEels i tried this technique but it gives an error of missing return statement. return is only done if ship is successfully placed.

Then give it the necessary return statements. Your code has a bunch of returns nested inside of if statements. If none of the if statements are true, there’s a chance of the method ending without returning anything, and that’s not allowed.

One solution is to add a default return statement at the bottom of the method, but if this were my code, I’d chuck the entire method and re-write it, refactoring it into several smaller simpler methods, and getting user interaction out of this method.


Edit 2
Another problem I see is that you’re using recursion in a dangerous and unnecessary way:

  if (shipPos.length() > 3 || shipPos.length() < 2) {
     System.out.println("Inappropriate target. Please enter again");
     counter = plantNavy(myBattle, counter);
  }

Note that if erroneous input is entered, you’re calling the method again within the same method, but not realizing that even though the method will call again, after the recursive call returns, the original method will still run to completion with the erroneous input. My suggestion, avoid recursion here, and again refactoring and simplifying your code will help you to do this.

Instead, get user input in a separate method, verifying the input as it’s being obtained (a simple do-while loop will suffice), and then once all input necessary for the placement of a ship is obtained, call your method to place a ship without having any user input inside of it.


Edit 3
Next you’ll want to get rid of those magic numbers that you’re using, making your code a bear to understand and debug.

3

solved How to handle symbol not found compile error in java? [closed]