Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The last two files are input files (text) that will be read from Assignment8 cla

ID: 3569445 • Letter: T

Question

The last two files are input files (text) that will be read from Assignment8 class. Save all files in the same folder. You will be creating a class called Ocean. This class should be defined in a file named "Ocean.java". The class Ocean will contain a two-dimensional array called "grids" of integers and another one-dimensional array called "ships" of Ship objects. It also has two static variables, gridWidth and gridHeight.

public Ocean(int a, int b, int c)

It instantiates the two dimensional array grids. The column and row are defined by the input first and second parameters respectively. It also instantiates the one-dimensional array ships of Ship objects with the size specified by the third input. Each ship object is constructed by using the Ship's default constructor, Ship().

Two static variables, gridWidth and gridHeight are initialized using the first and second inputs also. (3 pts)

public void setShips(String[] data)

It reads an array of strings and updates all elements in the ships. Each string element in the input, which includes the index, x position, y position, name, and safe condition of ship such as "1 5 5 Titanic false", will be used as an argument for Ship's setShip(String) method. (3 pts)

public boolean isSafe()

It returns true if and only if all ships are in safe. In other word, it returns false if there is at least one ship that is in trouble/distress. Use the Ship's getSafe() method. (2 pts)

private Ship getShip(int index)

It searches a Ship object, which has the shipID equal to the input. Use the Ship's getID() method to get the shipID value. (3 pts)

public void message (int index, char command )

It sends a message to a Ship object to move a direction. Find a Ship with the index by using the Ocean's getShip(index) method above, and apply the Ship's move(command) method to it. If the move(command) returns true, then display the message with the ship's name and its new position like below.

d [Queens moved to (3, 1)]

Otherwise, it displays the following message. (3 pts)

The ship cannot move to the direction.

public void updateSafe()

It checks and updates the isSafe conditions of all ships. If a safe ship is next to the ship in-trouble, then the ship will be saved by setting the isSafe as true. Check all ships each other (use two for-loops), and if and only if 1) one ship is safe and another is not safe, AND 2) the distance is 1, then set the isSafe of ship in-trouble as true and display the following message. (3 pts)

The Titanic is saved.

public void printInfo()

It updates the value of grids and displays symbols corresponding to the values. If there is no ship at the (x, y), the value of grid[y][x] is zero and the symbol is '*'. If there is a safe ship at the position, then the value and symbol is the index of ship (use the Ship's getID() method). If there is a ship in-trouble, then the value is -1 and the symbol is 'X'. The following is a case when a ship (id = 1) is at (0, 0) and a ship in trouble is at (4, 4). (3 pts)

           1   *   *   *   *

           *   *   *   *   *

           *   *   *   *   *

           *   *   *   *   *
           *   *   *   *   X

*****

public class Ship{

   private int xpos, ypos; // position of ship
   private int shipID; // index of ship
   private String name; // name of ship
   private boolean isSafe; // isSafe or not

// default constructor
   public Ship(){ xpos =0; ypos =0; shipID=0; name=""; isSafe=true; }
// set all instance variables using the ship information as a string.
   public void setShip(String str){
       String[] items = str.split("[^a-zA-Z0-9]");
       shipID = Integer.parseInt(items[0]);
       xpos = Integer.parseInt(items[1]);
       ypos = Integer.parseInt(items[2]);
       name = items[3];
       if(items[4].equals("true")) isSafe=true;
       else isSafe=false;
   }
   public int getXpos(){return xpos;} // get the xposition
   public int getYpos(){return ypos;} // get the yposition
   public int getID(){return shipID;} //get the shipID
   public String getName() {return name;} // get the name of ship
   public boolean getSafe() {return isSafe;} // check whether it is safe or not
   public void setSafe(boolean _safe){isSafe= _safe;} //set the isSafe
   public int getDistance(Ship other){ // calculate the distance to the other ship
           return (int) (Math.abs (xpos - other.xpos) + Math.abs(ypos-other.ypos));
   }
   // move this ship to up, left, down, and right using 'w', 'a', 'd', and 's' command.
   // It return true if it can move. Otherwise, return false
   public boolean move (char _command){
       switch(_command){
           case 'w':
           if (ypos <= 0) return false;
           ypos--; return true;
           case 'a':
               if (xpos <= 0) return false;
               xpos--; return true;
           case 's':
               if(ypos >=Ocean.gridHeight-1) return false;
               ypos++; return true;
           case 'd':
               if(xpos >=Ocean.gridWidth-1) return false;
               xpos++; return true;
           default: return false;
       }
   }
}

*****

import java.util.*;
import java.io.*;

public class Assignment8{
   public static void main(String[] arg) throws FileNotFoundException {

              Ocean    ocean;
              int oceanW, oceanH, shipNum;
              String line;
              Scanner in = new Scanner (System.in);
       char command; // command letter

              System.out.println(" ****** Program (Save ships) Starts ******");

              // ask a user to inpu the size of ocean width
       System.out.print(" Input the width of ocean:");
       oceanW = in.nextInt();
       // ask a user to input the size of ocean height
       System.out.print(" Input the hight of ocean:");
       oceanH = in.nextInt();
       // ask a user to input the file name for all ships
       System.out.print(" Input the name of data file:");
       String fileName = in.next();

       // Access to the file and create a Scanner object to read the text information
               File file = new File (fileName);
        Scanner inFile = new Scanner(file);

            line = inFile.nextLine(); // Read the first line showing the number of ships
            shipNum = Integer.parseInt(line);

            // Read each line and store the ship information into a string array
            String[] shipData = new String[shipNum];

            int count = 0;
       while (inFile.hasNextLine()) {
                   line = inFile.nextLine();
                      shipData[count] = line; // each line shows the information of each ship
                      count++;
               } // End of reading lines
               inFile.close(); // Close the file reader.

               // Create a Ocean object using the user inputs and file data
               ocean = new Ocean( oceanW, oceanH, shipNum); //*** Need Ocean(int, int, int) constructor
               ocean.setShips(shipData);                                                   //*** Need Ocean's setShip(int) method
               ocean.printInfo();                                                                   //*** Need Ocean's printInfo() method
               printMenu();

       do {
                          if (ocean.isSafe() ) { //*** Need Ocean's isSafe() method
                              System.out.println (" ****** All ships are saved ******");
                              break;
                           }
                           System.out.print(" ****** Save ships in-trouble ******");
                          System.out.print(" Input a command:");
                          command = in.next().charAt(0);

                          switch(command){
                              case 'w':    case 'a': case 's': case 'd':
                          System.out.print(" Input the index of ship to move: ");
                          if(!in.hasNextInt()) break;
                          int shipID = in.nextInt();
                              ocean.message(shipID, command); //*** Need Ocean's message(int, char) method
                              ocean.updateSafe();                                           //*** Need Ocean's updateSafe() method
                                  break;
                              case 'i':
                                  System.out.print(" i [Display the information]");
                                   ocean.printInfo();                                               //*** Need Ocean's printInfo() method
                                   break;
                              case '?': printMenu(); break;
                              case 'q': break;
                              default: System.out.print(" Invalid: *** Type '?' to get the commands***"); break;
                          }
              }while(command != 'q');

              System.out.println(" ****** End of Program ******");
   } // end of main ()

   // Display the command menu
   public static void printMenu(){
              System.out.println();
              System.out.println("Command Options --------------------");
              System.out.println("w: Move up");
              System.out.println("a: Move left");
              System.out.println("s: Move down");
              System.out.println("d: Move right");
              System.out.println("i: Display the information");
              System.out.println("?: Display this menu ");
              System.out.println("q: Quit the program");
              System.out.println("------------------------------------");
   }
}

*****

Explanation / Answer

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define MAX 50

int size;

// Defining the stack structure

struct stack {

  int arr[MAX];

  int top;

};

// Initializing the stack(i.e., top=-1)

void init_stk(struct stack *st) {

  st->top = -1;

}

// Entering the elements into stack

void push(struct stack *st, int num) {

  if (st->top == size - 1) {

     printf(" Stack overflow(i.e., stack full).");

     return;

  }

  st->top++;

  st->arr[st->top] = num;

}

//Deleting an element from the stack.

int pop(struct stack *st) {

  int num;

  if (st->top == -1) {

     printf(" Stack underflow(i.e., stack empty).");

     return NULL;

  }

  num = st->arr[st->top];

  st->top--;

  return num;

}

void display(struct stack *st) {

  int i;

  for (i = st->top; i >= 0; i--)

     printf(" %d", st->arr[i]);

}

int main() {

  int element, opt, val;

  struct stack ptr;

  init_stk(&ptr);

  printf(" Enter Stack Size :");

  scanf("%d", &size);

  while (1) {

     printf(" tSTACK PRIMITIVE OPERATIONS");

     printf(" 1.PUSH");

     printf(" 2.POP");

     printf(" 3.DISPLAY");

     printf(" 4.QUIT");

     printf(" ");

     printf(" Enter your option : ");

     scanf("%d", &opt);

     switch (opt) {

     case 1:

       printf(" Enter the element into stack:");

       scanf("%d", &val);

       push(&ptr, val);

       break;

     case 2:

       element = pop(&ptr);

       printf(" The element popped from stack is : %d", element);

       break;

     case 3:

       printf(" The current stack elements are:");

       display(&ptr);

       break;

     case 4:

       exit(0);

     default:

       printf(" Enter correct option!Try again.");

     }

  }

  return (0);

}

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define MAX 50

int size;

// Defining the stack structure

struct stack {

  int arr[MAX];

  int top;

};

// Initializing the stack(i.e., top=-1)

void init_stk(struct stack *st) {

  st->top = -1;

}

// Entering the elements into stack

void push(struct stack *st, int num) {

  if (st->top == size - 1) {

     printf(" Stack overflow(i.e., stack full).");

     return;

  }

  st->top++;

  st->arr[st->top] = num;

}

//Deleting an element from the stack.

int pop(struct stack *st) {

  int num;

  if (st->top == -1) {

     printf(" Stack underflow(i.e., stack empty).");

     return NULL;

  }

  num = st->arr[st->top];

  st->top--;

  return num;

}

void display(struct stack *st) {

  int i;

  for (i = st->top; i >= 0; i--)

     printf(" %d", st->arr[i]);

}

int main() {

  int element, opt, val;

  struct stack ptr;

  init_stk(&ptr);

  printf(" Enter Stack Size :");

  scanf("%d", &size);

  while (1) {

     printf(" tSTACK PRIMITIVE OPERATIONS");

     printf(" 1.PUSH");

     printf(" 2.POP");

     printf(" 3.DISPLAY");

     printf(" 4.QUIT");

     printf(" ");

     printf(" Enter your option : ");

     scanf("%d", &opt);

     switch (opt) {

     case 1:

       printf(" Enter the element into stack:");

       scanf("%d", &val);

       push(&ptr, val);

       break;

     case 2:

       element = pop(&ptr);

       printf(" The element popped from stack is : %d", element);

       break;

     case 3:

       printf(" The current stack elements are:");

       display(&ptr);

       break;

     case 4:

       exit(0);

     default:

       printf(" Enter correct option!Try again.");

     }

  }

  return (0);

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote