Question

ANNOTATE BRIEFLY LINE BY LINE THE FOLLOWING CODE: package shop.data; import junit.framework.Assert; import junit.framework.TestCase; public class...

ANNOTATE BRIEFLY LINE BY LINE THE FOLLOWING CODE:

package shop.data;

import junit.framework.Assert;
import junit.framework.TestCase;

public class DataTEST extends TestCase {
public DataTEST(String name) {
super(name);
}
public void testConstructorAndAttributes() {
String title1 = "XX";
String director1 = "XY";
String title2 = " XX ";
String director2 = " XY ";
int year = 2002;

Video v1 = Data.newVideo(title1, year, director1);
Assert.assertSame(title1, v1.title());
Assert.assertEquals(year, v1.year());
Assert.assertSame(director1, v1.director());

Video v2 = Data.newVideo(title2, year, director2);
Assert.assertEquals(title1, v2.title());
Assert.assertEquals(director1, v2.director());
}

public void testConstructorExceptionYear() {
try {
Data.newVideo("X", 1800, "Y");
Assert.fail();
} catch (IllegalArgumentException e) { }
try {
Data.newVideo("X", 5000, "Y");
Assert.fail();
} catch (IllegalArgumentException e) { }
try {
Data.newVideo("X", 1801, "Y");
Data.newVideo("X", 4999, "Y");
} catch (IllegalArgumentException e) {
Assert.fail();
}
}

public void testConstructorExceptionTitle() {
try {
Data.newVideo(null, 2002, "Y");
Assert.fail();
} catch (IllegalArgumentException e) { }
try {
Data.newVideo("", 2002, "Y");
Assert.fail();
} catch (IllegalArgumentException e) { }
try {
Data.newVideo(" ", 2002, "Y");
Assert.fail();
} catch (IllegalArgumentException e) { }
}

public void testConstructorExceptionDirector() {
}

}

package shop.data;

import java.util.Map;
import java.util.HashMap;
import java.util.Comparator;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import shop.command.Command;
import shop.command.UndoableCommand;
//import shop.data.InventorySet.RecordObj;
import shop.command.CommandHistory;
import shop.command.CommandHistoryFactory;
import shop.command.CommandHistoryObj;


/**
* Implementation of Inventory interface.
* @see Data
*/
final class InventorySet implements Inventory {
private Map<Video,Record> _data;
private final CommandHistory _history;

InventorySet() {
_data = new HashMap<Video,Record>();
_history = new CommandHistoryObj();

}

/**
* If <code>record</code> is null, then delete record for <code>video</code>;
* otherwise replace record for <code>video</code>.
*/
void replaceEntry(Video video, Record record) {
_data.remove(video);
if (record != null)
_data.put(video,((RecordObj)record).copy());
}

/**
* Overwrite the map.
*/
void replaceMap(Map<Video,Record> data) {
_data = data;
}

public int size() {
// TODO
return _data.size();
}

public Record get(Video v) {
// TODO
return _data.get(v);
}

public Iterator<Record> iterator() {
return Collections.unmodifiableCollection(_data.values()).iterator();
}

public Iterator<Record> iterator(Comparator<Record> comparator) {
   List<Record> res = new ArrayList<Record>(_data.values());
   Collections.sort(res, comparator);
   return Collections.unmodifiableCollection(res).iterator();
}

/**
* Add or remove copies of a video from the inventory.
* If a video record is not already present (and change is
* positive), a record is created.
* If a record is already present, <code>numOwned</code> is
* modified using <code>change</code>.
* If <code>change</code> brings the number of copies to be less
* than one, the record is removed from the inventory.
* @param video the video to be added.
* @param change the number of copies to add (or remove if negative).
* @return A copy of the previous record for this video (if any)
* @throws IllegalArgumentException if video null or change is zero
*/
Record addNumOwned(Video video, int change) {
if (video == null || change == 0)
throw new IllegalArgumentException();
  
RecordObj r = (RecordObj) _data.get(video);
if (r == null && change < 1) {
throw new IllegalArgumentException();
} else if (r == null) {
_data.put(video, new RecordObj(video, change, 0, 0));
} else if (r.numOwned+change < r.numOut) {
throw new IllegalArgumentException();
} else if (r.numOwned+change < 1) {
_data.remove(video);
} else {
_data.put(video, new RecordObj(video, r.numOwned + change, r.numOut, r.numRentals));
}
return r;
}

/**
* Check out a video.
* @param video the video to be checked out.
* @return A copy of the previous record for this video
* @throws IllegalArgumentException if video has no record or numOut
* equals numOwned.
*/
Record checkOut(Video video) {
   RecordObj r = (RecordObj) _data.get(video);
  
   if (r==null || r.numOut == r.numOwned)
       throw new IllegalArgumentException();
  
   _data.put(video, new RecordObj(video, r.numOwned, r.numOut+1, r.numRentals+1));
   return r;
}
  
/**
* Check in a video.
* @param video the video to be checked in.
* @return A copy of the previous record for this video
* @throws IllegalArgumentException if video has no record or numOut
* non-positive.
*/
Record checkIn(Video video) {
   RecordObj r = (RecordObj) _data.get(video);
  
   if (r==null || r.numOut==0)
       throw new IllegalArgumentException();
  
   _data.put(video, new RecordObj(video, r.numOwned, r.numOut-1, r.numRentals));
   return r;
}
  
/**
* Remove all records from the inventory.
* @return A copy of the previous inventory as a Map
*/
Map clear() {
// TODO
   Map<Video,Record> v = _data;
   _data = new HashMap<Video,Record>();
   return v;
}

/**
* Return a reference to the history.
*/
CommandHistory getHistory() {
// TODO
return _history;
}
  
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Database:\n");
Iterator i = _data.values().iterator();
while (i.hasNext()) {
buffer.append(" ");
buffer.append(i.next());
buffer.append("\n");
}
return buffer.toString();
}


/**
* Implementation of Record interface.
*
* <p>This is a utility class for Inventory. Fields are mutable and
* package-private.</p>
*
* <p><b>Class Invariant:</b> No two instances may reference the same Video.</p>
*
* @see Record
*/
private static final class RecordObj implements Record {
Video video; // the video
int numOwned; // copies owned
int numOut; // copies currently rented
int numRentals; // total times video has been rented
  
RecordObj(Video video, int numOwned, int numOut, int numRentals) {
this.video = video;
this.numOwned = numOwned;
this.numOut = numOut;
this.numRentals = numRentals;
}
RecordObj copy() {
return new RecordObj(video, numOwned, numOut, numRentals);
}
public Video video() {
return video;
}
public int numOwned() {
return numOwned;
}
public int numOut() {
return numOut;
}
public int numRentals() {
return numRentals;
}
public boolean equals(Object thatObject) {
return video.equals(((Record)thatObject).video());
}
public int hashCode() {
return video.hashCode();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(video);
buffer.append(" [");
buffer.append(numOwned);
buffer.append(",");
buffer.append(numOut);
buffer.append(",");
buffer.append(numRentals);
buffer.append("]");
return buffer.toString();
}
}

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


// Adding comment for each line
// DataTEST class is in package shop.data, so it can be referred as shop.data.DataTEST
package shop.data;

// importing the Assert and TestCase class of junit library
import junit.framework.Assert;
import junit.framework.TestCase;

// DataTEST class is extending the TestCase class of junit library,
// so it can access all members of the TestCase class
public class DataTEST extends TestCase {

// Below is the custom constructor of the DataTEST class which takes string as a argument
public DataTEST(String name) {
//calls to its parent(TestCase) constructor with string parameter
super(name);
}

// test method for validating the constructor and it its attributes
public void testConstructorAndAttributes() {
// creating and assinging values to String variables
String title1 = "XX";
String director1 = "XY";
String title2 = " XX ";
String director2 = " XY ";
// creating new int variable
int year = 2002;

// creating new instatnce of type video by passing 3 parameter to newVideo() method of Data class.
Video v1 = Data.newVideo(title1, year, director1);

// it will check if both the parameter are same, in below case they are same so it will fail
Assert.assertSame(title1, v1.title());

// it will check if both the parameter are equal, in below case they are equal so it will fail
Assert.assertEquals(year, v1.year());

// it will check if both the parameter are same, in below case they are same so it will fail
Assert.assertSame(director1, v1.director());

// creating new instatnce of type video by passing 3 parameter to newVideo() method of Data class.
Video v2 = Data.newVideo(title2, year, director2);
// it will check if both the parameter are equal, in below case they are not equal so it will pass
Assert.assertEquals(title1, v2.title());
// it will check if both the parameter are equal, in below case they are not equal so it will pass
Assert.assertEquals(director1, v2.director());
}

// test method for validating the year argument of constructor
public void testConstructorExceptionYear() {
// try block starts
try {
// calling newVideo method of Data class
Data.newVideo("X", 1800, "Y");
//The Assert.Fail method provides you with the ability to generate a failure based on tests
// that are not encapsulated by the other methods
Assert.fail();
}
// catch block will be executed if IllegalArgumentException is thrown by catch block
catch (IllegalArgumentException e) {
// catch block will nothing
}
try {
Data.newVideo("X", 5000, "Y");
Assert.fail();
}
// catch block will be executed if IllegalArgumentException is thrown by catch block
catch (IllegalArgumentException e) { }
try {
Data.newVideo("X", 1801, "Y");
Data.newVideo("X", 4999, "Y");
}
// catch block will be executed if IllegalArgumentException is thrown by catch block
catch (IllegalArgumentException e) {
// catch block, if executed will fail the execution
Assert.fail();
}
}

// test method for validating the Title argument of constructor
public void testConstructorExceptionTitle() {
try {
// passing null value for title parameter to constructor
Data.newVideo(null, 2002, "Y");
Assert.fail();
}
// catch block will be executed if IllegalArgumentException is thrown by catch block
catch (IllegalArgumentException e) { }
try {
// passing empty string value for title parameter to constructor
Data.newVideo("", 2002, "Y");
Assert.fail();
} catch (IllegalArgumentException e) { }
try {
// passing space value for title parameter to constructor
Data.newVideo(" ", 2002, "Y");
Assert.fail();
} catch (IllegalArgumentException e) { }
}

// empty method which will do nothing if called
public void testConstructorExceptionDirector() {
}

}


package shop.data;

// importing util library classes
import java.util.Map;
import java.util.HashMap;
import java.util.Comparator;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
// importing classes of shop package
import shop.command.Command;
import shop.command.UndoableCommand;
//import shop.data.InventorySet.RecordObj;
import shop.command.CommandHistory;
import shop.command.CommandHistoryFactory;
import shop.command.CommandHistoryObj;


/**
* Implementation of Inventory interface.
* @see Data
*/
final class InventorySet implements Inventory {
// creating map of Video as key and Record as value
private Map<Video,Record> _data;
// creating final variable
private final CommandHistory _history;

// constructor of the class which is setting the instance variable
InventorySet() {
_data = new HashMap<Video,Record>();
_history = new CommandHistoryObj();

}

/**
* If <code>record</code> is null, then delete record for <code>video</code>;
* otherwise replace record for <code>video</code>.
*/
void replaceEntry(Video video, Record record) {
_data.remove(video);
if (record != null)
_data.put(video,((RecordObj)record).copy());
}

/**
* Overwrite the map.
*/
void replaceMap(Map<Video,Record> data) {
_data = data;
}

public int size() {
// return the size of _data map
return _data.size();
}

public Record get(Video v) {
// return record from _data map having key as the parameter
return _data.get(v);
}

// return Iterator for Record list which are present in the _data map
public Iterator<Record> iterator() {
return Collections.unmodifiableCollection(_data.values()).iterator();
}

// return Iterator for sorted Record list of Record objects which are present in the _data map
public Iterator<Record> iterator(Comparator<Record> comparator) {
List<Record> res = new ArrayList<Record>(_data.values());
Collections.sort(res, comparator);
return Collections.unmodifiableCollection(res).iterator();
}

/**
* Add or remove copies of a video from the inventory.
* If a video record is not already present (and change is
* positive), a record is created.
* If a record is already present, <code>numOwned</code> is
* modified using <code>change</code>.
* If <code>change</code> brings the number of copies to be less
* than one, the record is removed from the inventory.
* @param video the video to be added.
* @param change the number of copies to add (or remove if negative).
* @return A copy of the previous record for this video (if any)
* @throws IllegalArgumentException if video null or change is zero
*/
Record addNumOwned(Video video, int change) {
if (video == null || change == 0)
throw new IllegalArgumentException();
  
RecordObj r = (RecordObj) _data.get(video);
if (r == null && change < 1) {
throw new IllegalArgumentException();
} else if (r == null) {
_data.put(video, new RecordObj(video, change, 0, 0));
} else if (r.numOwned+change < r.numOut) {
throw new IllegalArgumentException();
} else if (r.numOwned+change < 1) {
_data.remove(video);
} else {
_data.put(video, new RecordObj(video, r.numOwned + change, r.numOut, r.numRentals));
}
return r;
}

/**
* Check out a video.
* @param video the video to be checked out.
* @return A copy of the previous record for this video
* @throws IllegalArgumentException if video has no record or numOut
* equals numOwned.
*/
Record checkOut(Video video) {
RecordObj r = (RecordObj) _data.get(video);
  
if (r==null || r.numOut == r.numOwned)
throw new IllegalArgumentException();
  
_data.put(video, new RecordObj(video, r.numOwned, r.numOut+1, r.numRentals+1));
return r;
}
  
/**
* Check in a video.
* @param video the video to be checked in.
* @return A copy of the previous record for this video
* @throws IllegalArgumentException if video has no record or numOut
* non-positive.
*/
Record checkIn(Video video) {
RecordObj r = (RecordObj) _data.get(video);
  
if (r==null || r.numOut==0)
throw new IllegalArgumentException();
  
_data.put(video, new RecordObj(video, r.numOwned, r.numOut-1, r.numRentals));
return r;
}
  
/**
* Remove all records from the inventory.
* @return A copy of the previous inventory as a Map
*/
Map clear() {
// TODO
Map<Video,Record> v = _data;
_data = new HashMap<Video,Record>();
return v;
}

/**
* Return a reference to the history.
*/
CommandHistory getHistory() {
// return _history instance variable of class
return _history;
}
  
// overriding the toString() method of Java.lang.Object
public String toString() {
// creating string buffer variable
StringBuffer buffer = new StringBuffer();
// append Database in the string buffer
buffer.append("Database:\n");
// creating iterator for the list of Record objects which are present in the _data map
Iterator i = _data.values().iterator();
// appending space
while (i.hasNext()) {
// appending space in buffer
buffer.append(" ");
// appending value of record objects from the list in buffer
buffer.append(i.next());
// appending new line in buffer
buffer.append("\n");
}
// return the string value of buffer
return buffer.toString();
}


/**
* Implementation of Record interface.
*
* <p>This is a utility class for Inventory. Fields are mutable and
* package-private.</p>
*
* <p><b>Class Invariant:</b> No two instances may reference the same Video.</p>
*
* @see Record
*/
private static final class RecordObj implements Record {
Video video; // the video
int numOwned; // copies owned
int numOut; // copies currently rented
int numRentals; // total times video has been rented
  
// constructor for the RecordObj class
RecordObj(Video video, int numOwned, int numOut, int numRentals) {
this.video = video;
this.numOwned = numOwned;
this.numOut = numOut;
this.numRentals = numRentals;
}
RecordObj copy() {
return new RecordObj(video, numOwned, numOut, numRentals);
}
public Video video() {
return video;
}
public int numOwned() {
return numOwned;
}
public int numOut() {
return numOut;
}
public int numRentals() {
return numRentals;
}
// overriding the equals method of java.lang.object
public boolean equals(Object thatObject) {
return video.equals(((Record)thatObject).video());
}
// overriding the hashCode method of java.lang.object
public int hashCode() {
return video.hashCode();
}
// overriding the toString method of java.lang.object
// it returns the string containing values of all the instance variable
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(video);
buffer.append(" [");
buffer.append(numOwned);
buffer.append(",");
buffer.append(numOut);
buffer.append(",");
buffer.append(numRentals);
buffer.append("]");
return buffer.toString();
}
}

Add a comment
Know the answer?
Add Answer to:
ANNOTATE BRIEFLY LINE BY LINE THE FOLLOWING CODE: package shop.data; import junit.framework.Assert; import junit.framework.TestCase; public class...
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
  • package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic *...

    package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic * collection to store elements where indexes represent priorities and the * priorities can change in several ways. * * This collection class uses an Object[] data structure to store elements. * * @param <E> The type of all elements stored in this collection */ // You will have an error until you have have all methods // specified in interface PriorityList included inside this...

  • package scheduler; import java.util.List; public class Scheduler { /** * Instantiates a new, empty scheduler. */...

    package scheduler; import java.util.List; public class Scheduler { /** * Instantiates a new, empty scheduler. */ public Scheduler() { } /** * Adds a course to the scheduler. * * @param course the course to be added */ public void addCourse(Course course) { } /** * Returns the list of courses that this scheduler knows about. * * This returned object does not share state with the internal state of the Scheduler. * * @return the list of courses */...

  • /** * Notes: * You must use RECURSION to solve the problems. Your code may not...

    /** * Notes: * You must use RECURSION to solve the problems. Your code may not contain any loops. * You may not change any of the fields, nor the constructor, nor the insertAtFront method. * You may not modify the method headers given to you in any way nor may you change the name of the class or the package. */ package hw8; import java.util.NoSuchElementException; public class MyList<Item> {    private class MyListNode {        public Item item;...

  • package com.spartasystems.interview; public class FloorPlan { private final int width; private final int length; public FloorPlan(int...

    package com.spartasystems.interview; public class FloorPlan { private final int width; private final int length; public FloorPlan(int length, int width){ this.width = width; this.length = length; } } package com.spartasystems.interview; import java.util.ArrayList; import java.util.List; import java.util.Map; public class FloorPlanUtility { /** * Given a map of building names and floor plans and a number 'n', * return a list of 'n' building names that were mapped to the * FloorPlans with the largest areas * * Things to consider: * *...

  • Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements...

    Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements DictionaryInterface<K, V> { private int numEntries; private static final int DEFAULT_CAPACITY = 5; private static final int MAX_CAPACITY = 10000; private TableEntry<K, V>[] table; private double loadFactor; private static final double DEFAULT_LOAD_FACTOR = 0.75; public HashTableOpenAddressing() { this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR); } public HashTableOpenAddressing(int initialCapacity, double loadFactorIn) { numEntries = 0; if (loadFactorIn <= 0 || initialCapacity <= 0) { throw new IllegalArgumentException("Initial capacity and load...

  • Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException;...

    Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class BSTTreeNode{    BSTTreeNode left, right;    String data; public BSTTreeNode(){    left = null;    right = null;    data = null; } public BSTTreeNode(String n){    left = null;    right = null;    data = n; } public void setLeft(BSTTreeNode n){    left = n; } public void setRight(BSTTreeNode n){   ...

  • I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public...

    I need help running this code. import java.util.*; import java.io.*; public class wordcount2 {     public static void main(String[] args) {         if (args.length !=1) {             System.out.println(                                "Usage: java wordcount2 fullfilename");             System.exit(1);         }                 String filename = args[0];               // Create a tree map to hold words as key and count as value         Map<String, Integer> treeMap = new TreeMap<String, Integer>();                 try {             @SuppressWarnings("resource")             Scanner input = new Scanner(new File(filename));...

  • Complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    Complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * This returns a string containing the char ch, count times. * For example calling with 'a', 5 would return: * "aaaaa" * * @param ch The character to repeat. * @param count The number of the character. * @return A string with count number of ch. */ public static String charToString(char ch, int count) { return null; //TODO }   

  • PLEASE HURRY Software Testing Don't make any changes to the provided code. Please write a test...

    PLEASE HURRY Software Testing Don't make any changes to the provided code. Please write a test case for the below prompt using the provided java programs Use the setString() function in MyCustomStringInterface to set the value to “Peter Piper picked a peck of pickled peppers.”. Then test to see if reverseNCharacters() function returns the reversed string when the characters are reversed in groups of 4 and padding is disabled (in this case, “etePiP r repkcipa decep fo kcip delkpep srep.”)....

  • Must comment on the code at every "/* Comment Here */" section about what the code...

    Must comment on the code at every "/* Comment Here */" section about what the code is doing. import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import java.util.Map; import java.util.HashMap; public class Configuration extends DefaultHandler { private Map map; private String configurationFile; /* Comment Here */ public Configuration(String configurationFile) throws ConfigurationException {    this.configurationFile = configurationFile;    map = new HashMap();    try {    // Use the default (non-validating) parser    SAXParserFactory factory = SAXParserFactory.newInstance();...

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