Question

Write a program to pack boxes with blobs. Write two classes and a driver program. A...

Write a program to pack boxes with blobs. Write two classes and a driver program.

A Blob class

implements the following interface. (Defines the following methods.)
public interface BlobInterface {
/** getWeight accessor method.
@return the weight of the blob as a double
*/
public double getWeight();
/** toString method
@return a String showing the weight of the Blob
*/
public String toString();
}

A Blob must be between 1 and 4 pounds, with fractional weights allowed.

A default constructor creates a Blob with a weight of 2 pounds.

A one-double-parameter constructor creates a Blob with that many pounds, or throws an IllegalArgumentException if the weight is less than 1 or greater than 4 pounds.

A Box class

implements the following interface. (Note that, since the Blob class implements BlobInterface, then a Blob is a BlobInterface, so a Blob can be passed to the insert method below.)
public interface BoxInterface {
/** insert inserts a Blob into the box
@param b the Blob to insert
@return true if the blob fits, or false if it doesn't
*/
public boolean insert(BlobInterface b);

/** remainingCapacity accessor method
@return the remaining capacity of the box (how many more pounds it can hold).
*/
public double remainingCapacity();

/** toString
@return a String listing all of the Blobs in the Box, followed by the total weight
*/
public String toString();
}

A default constructor gives a Box capable of holding up to 25 pounds of Blobs.

An one-int-parameter constructor creates a Box capable of holding that number of pounds, but throws an IllegalArgumentException for 0 or negative arguments.

The driver program should

Instantiate 5 25-pound-capacity Boxes and

30 Blobs with weights that are random doubles from 1 to 4 (Math.random()*3+1).

Put the 30 Blobs into the boxes, filling the first box, then the second, etc., and then printing out each box.

Every Blob that is instantiated must be inserted into a Box.

The driver may be a console or GUI application.

Note that the driver program might not use some of the methods or constructors. You should define them anyway. Also, use ArrayLists rather than arrays.

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

Here is your program.

Code (Screenshot: Blob.java)

package com.masoomyf public class Blob implements BlobInterface //for storing its weight. //if weight never change in future

Box.java

ava.util.azzayLict ovs.util.ict toin hlub ee to u :(capacity 01 cepacity: w cen tha capacity ining ap builon .app Ld(ELob .

Main.java (Driver class)

package com.masoomy import java.util.ArrayList: import java.util.List: public class Main ( public static void main(Stringi] a

Code (Text Version)

BlobInterface.java

public interface BlobInterface {
    double getWeight();
    String toString();

}

BoxInterface.java

public interface BoxInterface {
    boolean insert(BlobInterface b);
    double remainingCapacity();
    String toString();
}

Blob.java

package com.masoomyf;

public class Blob implements BlobInterface {

    //for storing it's weight.
    //if weight never change in future, add keyword final
    private double weight;

    //Default constructor
    public Blob(){
        weight = 2.0;
    }


    //Constructor with weight parameter.
    public Blob(double weight) {
        //Checking if the param weight is less than 1 or more than 4.
        //If yes throw the exception.
        if(weight <1 || weight > 4){
            throw new IllegalArgumentException();
        }
        //assign this weight from parameter.
        this.weight = weight;
    }


    //Interface method, return the weight of blob.
    @Override
    public double getWeight() {
        return weight;
    }


    //Interface method, return weight to pound.
    @Override
    public String toString() {
        return "" + weight + " pound";
        //You can use this for nice output like 23.25 pound,
        // instead of 23.256365962010555 pound.
        // return String.format("%.2f pound",weight);
    }
}

Box.java

import java.util.ArrayList;
import java.util.List;

/**
 * com.masoomyf created by masoomyf on 26-01-2018.
 */
public class Box implements BoxInterface {

    //Storing capacity, assume that it will never change, once assigned.
    private final double capacity;
    //For storing the currently use space.
    //It will increase when new blob will add.
    private double usedSpace;

    //For storing blob
    private List<Blob> blobs;


    //Default constructor which assign capacity to 25
    //initialize blob's array list.
    //and assign used space to 0.
    public Box(){
        capacity = 25.0;
        blobs = new ArrayList<>();
        usedSpace = 0;
    }

    //Constructor with param capacity, which is integer as state in question.
    public Box(int capacity){
        //check is capacity is non-zero and non-negative.
        //if not throw new IllegalArgumentException.
        if(capacity <= 0){
            throw new IllegalArgumentException();
        }
        //Initialize this capacity with parameter one.
        this.capacity = capacity;

        blobs = new ArrayList<>();
        usedSpace = 0;
    }



    //Interface method.
    @Override
    public boolean insert(BlobInterface b) {
        //check if currently used space + blob weight which is to be add is
        //not more than the capacity.
        //If it is, return false.
        if(usedSpace+b.getWeight() > capacity)
            return false;

        //Else
        //Add the blob by casting it to Blob.
        //because parameter giving the blob but in BlobInterface type.
        //So cast it.
        blobs.add((Blob) b);
        //Add the blob weight to usedSpace.
        usedSpace += b.getWeight();
        //Return true, means blob is added.
        return true;

    }

    //Override method, return the remaining capacity.
    @Override
    public double remainingCapacity() {
        return capacity-usedSpace;
    }


    //To string method. (interface method)
    //It is also default override method for all object.
    @Override
    public String toString() {
        //Create new StringBuilder.
        //String builder can easily build string from many parts of string, integer etc.
        //Better to use stringBuilder rather than String s = "test";
        //s = s + "test1";   It's a bad practise and take more memory.

        StringBuilder builder = new StringBuilder();

        //Loop through each blob and print it's weight.
        //By using blob.toString() method, override at Blob.
        for (int i = 0; i < blobs.size(); i++) {
            Blob blob = blobs.get(i);
            builder.append("Blob ").append(blob.toString());
            //Check if it is last blob.
            //If yes put "." else put ", "
            if(i == blobs.size() - 1)
                builder.append(".");
            else
                builder.append(", ");
        }

        //Finally add the total weight to string builder.
        builder.append("Total Weight: ").append(usedSpace);

        //Now build the string and return it.
        return builder.toString();
    }
}

Main.java

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        //Creating box list.
        List<Box> boxList = new ArrayList<>();
        //Creating blob list.
        List<Blob> blobList = new ArrayList<>();

        //Addding 5 boxes to boxList with default constructor, that will
        //auto make it's capacity to 25 pound.
        for (int i=0;i<5;i++)
            boxList.add(new Box());

        //Adding 30 blob to blobList, with random value between 1-4;
        for (int i=0;i<30;i++){
            Blob blob = new Blob((Math.random() * 3) + 1);
            blobList.add(blob);
        }

        //Flag the current box uses.
        int boxInUseIndex = 0;

        //Loop through each blob to insert into box.
        for (Blob blob:blobList){
            //Flag first the current blob is not added.
            boolean isAdded = false;
            //Run while loop until it add.
            while (!isAdded){
                //add the current blob to box having index boxInUseIndex.
                //If it is successful, isAdded become true and while loop break,
                //And next blob comes.
                isAdded = boxList.get(boxInUseIndex).insert(blob);
                if(!isAdded){
                    //If not successful,
                    // increase the box index by 1. (means next box)
                    boxInUseIndex++;
                }
            }

        }

        //Now loop through box and print its item(blob).
        for (Box box:boxList){
            System.out.println(box.toString());
            System.out.println("\n"); //Added two blank line for clear output.
        }
    }
}

Output

C:\Program Files\Javaljdkl.8.0 20 bin\java Blob 3.700415279098494, Blob 3.214989801203669, Blob 1.0619436527578667, Blob 1.

Add a comment
Know the answer?
Add Answer to:
Write a program to pack boxes with blobs. Write two classes and a driver program. A...
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
  • java questions: 1. Explain the difference between a deep and a shallow copy. 2. Given the...

    java questions: 1. Explain the difference between a deep and a shallow copy. 2. Given the below classes: public class Date {    private String month;    private String day;    private String year;    public Date(String month, String day, String year) {       this.month = month;       this.day = day;       this.year = year;    }    public String getMonth() {       return month;    }    public String getDay() {       return day;    }    public String...

  • Java file Name Dog Classes and Methods Create a constructor that incorporates the type, breed, and...

    Java file Name Dog Classes and Methods Create a constructor that incorporates the type, breed, and name variables (do not include topTrick). Note: The type refers to what the breed typically does; for example, a corgi would be a “cattle herding dog.” A Shiba Inu would be a “hunting dog.” Create the setTopTrick() mutator method Dog is parent class Corgi and Driver are subclasses Complete the Corgi class: Using the UML Class diagram, declare the instance variables. Create the two...

  • Please create two tests classes for the code down below that use all of the methods...

    Please create two tests classes for the code down below that use all of the methods in the Transaction class, and all of the non-inherited methods in the derived class. Overridden methods must be tested again for the derived classes. The first test class should be a traditional test class named "Test1" while the second test class should be a JUnit test class named "Test2". All I need is to test the classes, thanks! Use a package that contains the...

  • Java Programming --- complete the given classes DeLand Space Car Dealer needs a new program for...

    Java Programming --- complete the given classes DeLand Space Car Dealer needs a new program for their inventory management system. The program needs the following classes: A main class (SpaceCarDealer.java) that includes the main method and GUI. Two instantiable classes: CarDealer.java o Variables to store the dealer name, and the carsOnLot array in Car type. o A constructor to initialize the name variable with the given dealer name. o An accessor method to return the name of the dealer. o...

  • please write in Java and include the two classes Design a class named Fan (Fan.java) to...

    please write in Java and include the two classes Design a class named Fan (Fan.java) to represent a fan. The class contains: An int field named speed that specifies the speed of the fan. A boolean field named fanStatus that specifies whether the fan is on (default false). A double field named radius that specifies the radius of the fan (default 5). A string field named color that specifies the color of the fan (default blue). A no-arg (default) constructor...

  • Here is a sample run of the tester program: Make sure your program follows the Java...

    Here is a sample run of the tester program: Make sure your program follows the Java Coding Guidelines. Consider the following class: /** * A store superclass with a Name and Sales Tax Rate */ public class Store {      public final double SALES_TAX_RATE = 0.06;      private String name;           /**      * Constructor to create a new store      * @param newName      */      public Store(String newName)      {           name = newName;      }     ...

  • Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use impl...

    Implement the classes in the following class diagram. The Book class implements the Comparable interface. Use implements Comparable<Book> in the class definition. Now, all book objects are instances of the java.lang.Comparable interface. Write a test program that creates an array of ten books. 1. Use Arrays.sort( Book[]l books) from the java.util package to sort the array. The order of objects in the array is determined using compareTo...) method. 2. Write a method that returns the most expensive book in the...

  • Task 3: Main Program Create a main program class that: Creates three or more Nurse instances...

    Task 3: Main Program Create a main program class that: Creates three or more Nurse instances assigned to different shifts. Creates three or more Doctor instances. Creates three or more Patient instances with pre-determined names and manually assigned physicians chosen from the pool of Doctor instances previously created. Generates another 20 Patient instances using randomly generated names and randomly assigns them physicians chosen from the pool of Doctor instances previously created. Prints the toString() values for all employees. Prints the...

  • (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text...

    (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text file named pets10.txt with 10 pets (or use the one below). Store this file in the same folder as your “class” file(s). The format is the same format used in the original homework problem. Each line in the file should contain a pet name (String), a comma, a pet’s age (int) in years, another comma, and a pet’s weight (double) in pounds. Perform the...

  • [JAVA] < Instruction> You are given two classes, BankAccount and ManageAccounts ManageAccounts is called a Driver...

    [JAVA] < Instruction> You are given two classes, BankAccount and ManageAccounts ManageAccounts is called a Driver class that uses BankAccount. associate a member to BankAcount that shows the Date and Time that Accounts is created. You may use a class Date. To find API on class Date, search for Date.java. Make sure to include date information to the method toString(). you must follow the instruction and Upload two java files. BankAccount.java and ManageAccounts.java. -------------------------------------------------------------------------- A Bank Account Class File Account.java...

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