Question

In: Computer Science

Objective: Using Java coding language, complete each "TO-DO" section for the following classes. Shape code (for...

Objective: Using Java coding language, complete each "TO-DO" section for the following classes.

Shape code (for reference, nothing to complete here):

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.io.RandomAccessFile;

public abstract class Shape extends Rectangle {
   public int id;
   public Color color;
   public int xSpeed, ySpeed;
  
   public Shape(int id, int x, int y, int width, int height, Color color, int xSpeed, int ySpeed) {
       super(x,y,width,height);
       this.id = id;
       this.color = color;
       this.xSpeed = xSpeed;
       this.ySpeed = ySpeed;
   }
  
   public abstract void move(int screenWidth, int screenHeight);
   public abstract void draw(Graphics g);
   public abstract void save(RandomAccessFile raf) throws Exception;
  
}

Ball code:

import java.awt.Color;
import java.awt.Graphics;
import java.io.RandomAccessFile;

public class Ball extends Shape {

   public Ball(int id, int x, int y, int size, Color color, int xSpeed, int ySpeed) {
       super(id, x, y, size, size, color, xSpeed, ySpeed);
   }

   @Override
   public void move(int screenWidth, int screenHeight) {
       x += xSpeed;
       y += ySpeed;
      
       if(x > screenWidth) x = -width;
       else if(x + width < 0) x = screenWidth;
      
       if(y > screenHeight) y = -height;
       else if(y + height < 0) y = screenHeight;      
   }

   @Override
   public void draw(Graphics g) {
       g.setColor(color);
       g.fillOval(x, y, width, height);
       g.setColor(Color.BLACK);
       g.drawOval(x, y, width, height);
   }

   // TO-DO:    Write the code that saves out the type of object (Ball)
   //           and all data about the box ("Ball", id, x, y, width, height, color,
   //           xSpeed, and ySpeed)
   @
Override
   public void save(RandomAccessFile raf) throws Exception {
       // Note, when saving color you will save it as an int: color.getRGB()
   }
}

Box code:

import java.awt.Color;
import java.awt.Graphics;
import java.io.RandomAccessFile;
// is-a
public class Box extends Shape {

   public Box(int id, int x, int y, int size, Color color, int xSpeed, int ySpeed) {
       super(id, x, y, size, size, color, xSpeed, ySpeed);
   }

   @Override
   public void move(int screenWidth, int screenHeight) {
       x += xSpeed;
       y += ySpeed;
      
       if(x > screenWidth) x = -width;
       else if(x + width < 0) x = screenWidth;
      
       if(y > screenHeight) y = -height;
       else if(y + height < 0) y = screenHeight;
                      
   }

   @Override
   public void draw(Graphics g) {
       g.setColor(color);
       g.fillRect(x, y, width, height);
       g.setColor(Color.BLACK);
       g.drawRect(x, y, width, height);
   }

   // TO-DO:    Write the code that saves out the type of object (Box)
   //           and all data about the box ("Box", id, x, y, width, height, color,
   //           xSpeed, and ySpeed)

   @Override
   public void save(RandomAccessFile raf) throws Exception {
       // Note, when saving color you will save it as an int: color.getRGB()
   }

}

Solutions

Expert Solution

Data is saved into the file using writeBytes() method of RandomAccessFile object.

I have overridden the toString() method of Box & Ball classes which will return all the data as string and then finally saving it as bytes in save() method.  

Note: int value of color is taken care of in this method itself before saving. Appending '\n' to the result returned by toString() so that new record goes into new line (just to make file easily readable).

Screenshot of code and data.txt file are also attached.

Box.java

import java.awt.Color;
import java.awt.Graphics;
import java.io.RandomAccessFile;
// is-a
public class Box extends Shape {

    public Box(int id, int x, int y, int size, Color color, int xSpeed, int ySpeed) {
        super(id, x, y, size, size, color, xSpeed, ySpeed);
    }

    @Override
    public void move(int screenWidth, int screenHeight) {
        x += xSpeed;
        y += ySpeed;

        if(x > screenWidth) x = -width;
        else if(x + width < 0) x = screenWidth;

        if(y > screenHeight) y = -height;
        else if(y + height < 0) y = screenHeight;

    }

    @Override
    public void draw(Graphics g) {
        g.setColor(color);
        g.fillRect(x, y, width, height);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, width, height);
    }

    // TO-DO:    Write the code that saves out the type of object (Box)
    //           and all data about the box ("Box", id, x, y, width, height, color,
    //           xSpeed, and ySpeed)
    @Override
    public void save(RandomAccessFile raf) throws Exception {
        // Note, when saving color you will save it as an int: color.getRGB()
        raf.writeBytes(this.toString());
    }

    @Override
    public String toString() {
        return "(Box, id:" + this.id + ", x:" + this.x + ", y:" + this.y + ", width:" + this.width + ", height:" + this.height + ", color:" + this.color.getRGB()
                + ", xSpeed:" + this.xSpeed + ", ySpeed:" + this.ySpeed +  ")\n";
    }
}

Ball.java

import java.awt.Color;
import java.awt.Graphics;
import java.io.RandomAccessFile;

public class Ball extends Shape{

    public Ball(int id, int x, int y, int size, Color color, int xSpeed, int ySpeed) {
        super(id, x, y, size, size, color, xSpeed, ySpeed);
    }

    @Override
    public void move(int screenWidth, int screenHeight) {
        x += xSpeed;
        y += ySpeed;

        if(x > screenWidth) x = -width;
        else if(x + width < 0) x = screenWidth;

        if(y > screenHeight) y = -height;
        else if(y + height < 0) y = screenHeight;
    }

    @Override
    public void draw(Graphics g) {
        g.setColor(color);
        g.fillOval(x, y, width, height);
        g.setColor(Color.BLACK);
        g.drawOval(x, y, width, height);
    }

    // TO-DO:    Write the code that saves out the type of object (Ball)
    //           and all data about the box ("Ball", id, x, y, width, height, color,
    //           xSpeed, and ySpeed)
    @Override
    public void save(RandomAccessFile raf) throws Exception {
        // Note, when saving color you will save it as an int: color.getRGB()
        raf.writeBytes(this.toString());
    }

    @Override
    public String toString() {
        return "(Ball, id:" + this.id + ", x:" + this.x + ", y:" + this.y + ", width:" + this.width + ", height:" + this.height + ", color:" + this.color.getRGB()
                + ", xSpeed:" + this.xSpeed + ", ySpeed:" + this.ySpeed +  ")\n";
    }
}

Shape.java

No changes in this file.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.io.RandomAccessFile;

public abstract class Shape extends Rectangle {
    public int id;
    public Color color;
    public int xSpeed, ySpeed;

    public Shape(int id, int x, int y, int width, int height, Color color, int xSpeed, int ySpeed) {
        super(x,y,width,height);
        this.id = id;
        this.color = color;
        this.xSpeed = xSpeed;
        this.ySpeed = ySpeed;
    }

    public abstract void move(int screenWidth, int screenHeight);
    public abstract void draw(Graphics g);
    public abstract void save(RandomAccessFile raf) throws Exception;

}

Main.java

I have written main() in this file to run and test the code.

Created two objects of Ball & Box classes and called save() on these objects. Data is being saved in the file named data.txt.

import java.awt.*;
import java.io.RandomAccessFile;

public class Main {

    public static void main(String[] args) throws Exception {
        Shape ball = new Ball(1, 2, 3, 4, Color.CYAN, 10, 15);
        Shape box = new Box(2, 4, 3, 9, Color.GREEN, 12, 11);
        RandomAccessFile raf = new RandomAccessFile("src/data.txt", "rw");

        ball.save(raf);
        box.save(raf);
    }
}

Data.txt

Below are the contents in the file after running the main().

(Ball, id:1, x:2, y:3, width:4, height:4, color:-16711681, xSpeed:10, ySpeed:15)
(Box, id:2, x:4, y:3, width:9, height:9, color:-16711936, xSpeed:12, ySpeed:11)


Related Solutions

Using python as the coding language please write the code for the following problem. Write a...
Using python as the coding language please write the code for the following problem. Write a function called provenance that takes two string arguments and returns another string depending on the values of the arguments according to the table below. This function is based on the geologic practice of determining the distance of a sedimentary rock from the source of its component grains by grain size and smoothness. First Argument Value Second Argument Value Return Value "coarse" "rounded" "intermediate" "coarse"...
Using the provided Java program below, complete the code to do the following. You may need...
Using the provided Java program below, complete the code to do the following. You may need to create other data items than what is listed for this assignment. The changes to the methods are listed in the comments above the method names. TODO comments exist. Apply any TODO tasks and remove the TODO comments when complete. Modify the method findMyCurrency() to do the following:    a. Use a do-while loop b. Prompt for a currency to find. c. Inside this...
Complete the following exercises using C programming language. Take screenshots of the code and its output...
Complete the following exercises using C programming language. Take screenshots of the code and its output where specified and paste them into in a well-labeled Word document for submission. Scenario Assume you are the CIO of an organization with three different IT department locations with separate costs. You want a program to perform simple IT expenditure calculations. Your IT expenditure target is $35,000 per site. Site expenditures: Site 1 – $35,000. Site 2 – $37,500. Site 3 – $42,500. Exercise...
URGENT!! DO THIS CODE IN JAVA Write a complete Java FX program that displays a text...
URGENT!! DO THIS CODE IN JAVA Write a complete Java FX program that displays a text label and a button.When the program begins, the label displays a 0. Then each time the button is clicked, the number increases its value by 1; that is each time the user clicks the button the label displays 1,2,3,4............and so on.
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
Java Solution Create a class hierarchy that represents shapes. It should have the following classes: Shape,...
Java Solution Create a class hierarchy that represents shapes. It should have the following classes: Shape, Two Dimensional Shape, Three Dimensional Shape, Square, Circle, Cube, Rectangular Prism, and Sphere. Cube should inherit from Rectangular Prism. The two dimensional shapes should include methods to calculate Area. The three dimensional shapes should include methods to calculate surface area and volume. Use as little methods as possible (total, across all classes) to accomplish this, think about what logic should be written at which...
Write code in java using the LinkedList connecting two different classes. For example, Employee and EmployeeList...
Write code in java using the LinkedList connecting two different classes. For example, Employee and EmployeeList are two different classes that are used to create the assignment.
USING JAVA: Complete the following class. input code where it says //TODO. public class BasicBioinformatics {...
USING JAVA: Complete the following class. input code where it says //TODO. public class BasicBioinformatics { /** * Calculates and returns the complement of a DNA sequence. In DNA sequences, 'A' and 'T' are * complements of each other, as are 'C' and 'G'. The complement is formed by taking the * complement of each symbol (e.g., the complement of "GTCA" is "CAGT"). * * @param dna a char array representing a DNA sequence of arbitrary length, * containing only...
Using existing Stack Java Collection Framework, write Java Code segment to do the following.   You may...
Using existing Stack Java Collection Framework, write Java Code segment to do the following.   You may write this in jGrasp Create a Stack of String called, myStacks Read input from keyboard, 10 names and then add to myStacks As you remove each name out, you will print the name in uppercase along with a number of characters the name has in parenthesis. (one name per line).   e.g.     Kennedy (7) Using existing Stack Java Collection Framework, write Java Code segment to...
Write a complete program in java that will do the following:
Write a complete program in java that will do the following:Sports:             Baseball, Basketball, Football, Hockey, Volleyball, WaterpoloPlayers:           9, 5, 11, 6, 6, 7Store the data in appropriate arraysProvide an output of sports and player numbers. See below:Baseball          9 players.Basketball       5 players.Football           11 players.Hockey            6 players.Volleyball        6 players.Waterpolo       7 players.Use Scanner to provide the number of friends you have for a team sport.Provide an output of suggested sports for your group of friends. If your...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT