Question

Looking at this method, it returns true if a given location contains a real ship that...

Looking at this method, it returns true if a given location contains a real ship that is still afloat. It says "real" ship because the 'emptySea' class extends Ship class with an inherited length of one, saving the need for null checks as empty locations now contain a non-null value meaning it does not contain a ship. 'isOccupied' will return true if that location contains a ship. The 'ships' array is used to determine which ship is in that location. 'allShips' is an ArrayList to which all ships were added too.

Given this information, I would like to understand how this method works - line by line. If someone could comment each line, that would be really helpful. Thank you.

public boolean shootAt(int row, int column) {
       int hit = 0;
       int sunkNum = 0;
       if (isOccupied(row, column) && !ships[row][column].isSunk()) {
           this.hitCount += 1;
           hit = 1;
       }
       this.shotsFired += 1;
       this.ships[row][column].shootAt(row, column);
       for (Ship ship: this.allShips) {
           if (ship.isSunk()){
               sunkNum += 1;
           }
       }
       this.shipsSunk = sunkNum;
       if (hit == 1) {
           return true;
       }
       return false;
   }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note :- The comments for the code mentioned above is provided between multiple line comment /* */ along with the code

/*it is a method named shootAt which is of Boolean type i.e. this method will return value “True” or “False” . It is a public method i.e. it can be used anywhere in any class . This method takes the parameter row and column of integer datatype which tells the position of the ship*/

public boolean shootAt(int row, int column)

{
       int hit = 0; //variable hit of integer datatype initialized with value ‘0’.
       int sunkNum = 0; // variable sunkNum of integer datatype initialized with value ‘0’.

     /*In this If check there are two conditions mentioned as below , which if are true then the code in IF block will execute :-

1st IF condition :- isOccupied(row, column) – the two parameters passed in the method shootAt are used in isOccupied() method to check if the ship is there or not . If isOccupied returns true then one condition in IF is satisfied else if it false then IF block is not executed as there is && between two conditions .

2nd IF condition : !ships[row][column].isSunk() :- Sunk() is a method defined which is used here to find whether the parameters passed for the ship in method shootAt(int row, int column) has sunk or not .

If the ship has not sunk means the condtion is not true and is still on water floating then second IF condition is also satisfied .

       if (isOccupied(row, column) && !ships[row][column].isSunk())

     // Once the IF conditions are satisfied then the if block is executed

     {
           this.hitCount += 1
; /* once the IF is satisfied that eans ship is still afloat and hitCount is incremented by 1*/
           hit = 1; // variable defined earlier is set to 1 which was earlier initialized to 0
       }


       this.shotsFired += 1;   /*method shootAt () also counts the shots fired at the ships . Therefore everytime shot is fired method shootAt () is executed , incrementing shotsFired by 1 each time .*/


       this.ships[row][column].shootAt(row, column);
/* this is a self calling loop where shootAt() method is called again till the time it shows no ship exist*/


       for (Ship ship: this.allShips) /* for loop is started for all the ships to find how many have sunk */

      {
           if (ship.isSunk())
/* If the ship has sunk i.e. method isSunk() returns true then the IF block code is executed */

         {
               sunkNum += 1;
/* if the ship has sunk then the variable sunkNum is incremented by to find the number of sunk ships*/
           }
       }
       this.shipsSunk = sunkNum;
// assign the sunkNum value to shipsSunk method as parameter
       if (hit == 1) /*hit variable is set to 1 when the IF condition “if (isOccupied(row, column) && !ships[row][column].isSunk()) is true “ . Therefore if hit is equal to 1 then the method shootAt returns true else it returns false*/

    {
           return true;
       }
       return false;
   }

Add a comment
Know the answer?
Add Answer to:
Looking at this method, it returns true if a given location contains a real ship that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every...

    Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every part, and include java doc and comments Create a battleship program. Include Javadoc and comments. Grade 12 level coding style using java only. You will need to create a Ship class, Location class, Grid Class, Add a ship to the Grid, Create the Player class, the Battleship class, Add at least one extension. Make sure to include the testers. Starting code/ sample/methods will be...

  • Given the following construct a UML diagram for Java: Design a class named location for locating...

    Given the following construct a UML diagram for Java: Design a class named location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximum value and its indices in a two-dimensional array with row and column as int types and maxValue as double type. Write the following method that returns the location of the largest element in two-dimensional array: Public static Location locateLargest(double[][] a)...

  • I need assistance with this method. Don't change the method type, decoding UTF8 import java.util.Scanner; /**...

    I need assistance with this method. Don't change the method type, decoding UTF8 import java.util.Scanner; /** * Determines if a sequence of cells of length len in a game board is clear or not. This is used * to determine if a ship will fit on a given game board. The x and y coordinates passed in as * parameters represent the top-left cell of the ship when considering the grid. * * @param board The game board to search....

  • Java question Write the method reversed that returns true if and only if the arrays a...

    Java question Write the method reversed that returns true if and only if the arrays a and b contain exactly the same elements, but in reversed order. For example, reversed ({3, 1}, {1, 3}) returns true, but reversed ({3, 1}, {2, 3}) and reversed ({3, 1}, {1, 1, 3}) both return false. public static boolean reversed (int [] a, int [] b) should return true if and only if a and b contain the same elements, reversed.

  • cant understand why my toString method wont work... public class Matrix { private int[][] matrix; /**...

    cant understand why my toString method wont work... public class Matrix { private int[][] matrix; /** * default constructor -- * Creates an matrix that has 2 rows and 2 columns */ public Matrix(int [][] m) { boolean valid = true; for(int r = 1; r < m.length && valid; r++) { if(m[r].length != m[0].length) valid = false; } if(valid) matrix = m; else matrix = null; } public String toString() { String output = "[ "; for (int i...

  • Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next...

    Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next two assignments you will be creating a one-player version of the game. The game is extremely simple. Each player arranges a fleet of ships in a grid. The grid is hidden from the opponent. Here is an ASCII representation of a 10x10 grid. The ‘X’s represent ships, the ‘~’s represent empty water. There are three ships in the picture: A vertical ship with a...

  • Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a...

    Modify the library program as follows: Create a method in the LibraryMaterial class that accepts a string s as a parameter and returns true if the title of the string is equal to s. Create the same method for your library material copies. Note that it will need to be abstract in the LibraryMaterialCopy class MY CODE **************************************************************** LibraryCard: import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import    java.time.temporal.ChronoUnit; public class LibraryCard {    private String id;    private String cardholderName;   ...

  • 1. Please fill in the cells according to the given statements for each row. If the...

    1. Please fill in the cells according to the given statements for each row. If the statement runs correctly, it returns true or false, in this case please state the output in the fourth column. If the statement gives an error (i.e. compile or runtime error), please indicate that by typing the corresponding column (2nd or 3rd column). For each item, please write a one-sentence explanation. Note that each row will contain only one result. (15 points in total) }...

  • JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

    JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {     /**      * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList      * containing all the indexes of Strings in arr that match String s. For this method, two Strings,      * p and q, match when p.equals(q) returns true or if both of the compared references are null.      *      * @param s The string...

  • /** * A collection of methods related to multi-dimensional arrays. */ public class Array2Lab { /**...

    /** * A collection of methods related to multi-dimensional arrays. */ public class Array2Lab { /** * Return whether k is in list. * Precondition: the elements of list are not null. * @param list the array to be searched. * @param k the number to search for. * @return true if k is an element of list, and false otherwise. */ public static boolean contains(Object[][] list, Object k) { return false; }    /** * Create a String that...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT