Hello, I need help with my code my addItem method doesn\'t expand the array when
ID: 3908806 • Letter: H
Question
Hello, I need help with my code my addItem method doesn't expand the array when the array is full. I attached my code and a test.java file (test 41) to check if it expands.
TODOList.java
/* This class encapsulates a list of user-defined items that should be done- a "TODO" list.
* Each item on the list is represented by a String object.
* The list is implemented by a String array. The array is initialized in the constructor to an
* initial length that is passed to the constructor. The initial array contains only NULL values.
* A user adds an item (a String) to the list by calling the addItem method, passing in a String
* that represents the to-do item.
* Thus, the array may have fewer items (Strings) than its length.
*
* For example, assume the list has an initial length of 5. It looks like this:
* NULL, NULL, NULL, NULL, NULL
*
* Then, a user adds three items. It looks like this:
* "eat lunch", "walk dog", "study Java", NULL, NULL
*
* The length of the list is 5, the number of items is 3. The NULL values are unoccupied cells.
* The capacity of the array is its length. The size of the data stored in the array is less than
* or equal to its capacity.
*
* If a user wants to add more items to a list that has no more NULL values, i.e. no more room,
* the expandArray method is called to double the length of the toDoList. The original Strings
* are in the same positions, but the new array has double the capacity- more room for adding items.
*/
public class TODOList {
/* YOUR Instance variable declarations here. */
private String[] TODO;
private int initialLength;
private int numItems;
/* Constructor that initializes the initialLength variable to the value passed in.
* It also initializes the toDoList with the initial length.
* Any other instance variables may be initialized as well.
*/
public TODOList(int initialLen)
{
this.initialLength = initialLen;
this.TODO = new String[initialLen];
this.numItems = 0;
}
/* Add the item passed in to the end of the list.
* For example, if the toDoList list contained: "eat lunch", "walk dog",
* the next item added, "study Java", would result in this list:
* "eat lunch", "walk dog", "study Java"
* Suggestion: use instance variable to keep track of the index of the next available cell.
*/
public void addItem(String itemStr)
{
if (TODO.length > numItems)
{
TODO[numItems] = itemStr;
numItems += 1;
}
}
/* Overwrite the item at "position" to be the parameter "itemStr".
* Note: position is a positive integer > 0 that has to be a valid position
* in the toDoList. A valid position corresponds to an item stored in the
* toDoList. For example, if this was the list:
1 walk the cat
2 order doughnuts
3 go to the gym
4 wash dishes
* valid positions would be 1, 2, 3, 4. All other integers are invalid.
* This method returns true if a valid position was passed in, false otherwise.
*/
public boolean replaceItemAt(String itemStr, int position)
{
if (position > 0 && position <= initialLength && TODO[position - 1] != null)
{
TODO[position - 1] = itemStr;
return true;
}
return false;
}
/* Remove the last item in the toDoList.
* For example, if the toDoList list contained: "eat lunch", "walk dog", "study Java",
* removing the last item would result in this list:
* "eat lunch", "walk dog".
* This method returns true if there is at least one item in the list,
* false otherwise.
*/
public boolean removeLastItem()
{
if (initialLength > 0 && numItems > 0)
{
numItems -= 1;
TODO[numItems] = null;
return true;
}
return false;
}
/*
* Return a list that contains only the items that have been added.
* This list does not contain any NULL values.
* For example, if the toDoList list contained: "eat lunch", "walk dog", "study Java", NULL, NULL
* This method would return this array: "eat lunch", "walk dog", "study Java"
* If the toDoList does not contain any items, this method returns a String array with zero length.
*/
public String[] getToDoList()
{
int numLoop = 0;
String[] result = new String[numItems];
while (numLoop < initialLength && TODO[numLoop] != null)
{
result[numLoop] = TODO[numLoop];
numLoop++;
}
return result;
}
/* Remove all items from the list, resulting in an empty list.
* The capacity of the list returns to the initial length.*/
public void clearToDoList()
{
int numLoop = 0;
while (numLoop < TODO.length && TODO[numLoop] != null)
{
TODO[numLoop] = null;
numItems -= 1;
numLoop++;
}
}
/* Returns a String representation of the current item list according to
* these specifications:
* Each item is on one line, position number first followed by one blank,
* followed by the item String.
* For example:
1 walk the cat
2 order doughnuts
3 go to the gym
4 wash dishes
* If no items are on the list the String returned is: "no items".*/
public String getToDoListAsString()
{
int numItems = 0;
String result = "";
if (TODO[0] == null)
{
result = "no items";
return result;
}
while (numItems < initialLength && TODO[numItems] != null) {
result = result +" " + TODO[numItems];
numItems++;
}
return result;
}
/* Returns the number of items stored in the item list.*/
public int getNumberOfItems(){
return numItems;
}
/* Returns true if the item list contains no items, false otherwise.*/
public boolean isEmpty(){
if (numItems > 0)
{
return false;
}
return true;
}
/****** Private, "helper" method section ******/
/* Creates a new array that is double the size of the array passed in, copies the data
* from that array to the new array, and returns the new array.
* Note that the new array will contain the items
*from the previous array followed by NULL values.*/
private String[] expandList(String[] inputList)
{
String[] newArray = new String[inputList.length * 2];
int numLoop = 0;
while (numLoop < inputList.length && inputList[numLoop] != null) {
newArray[numLoop] = inputList[numLoop];
numLoop++;
}
return newArray;
}
/* A full item list is an array where all cells contain an item. That
* means there is no cell that contains NULL.
* This method returns true if all cells in the array contain a String
* object, false otherwise.
*/
private boolean isFull()
{
if (numItems == TODO.length)
{
return true;
}
return false;
}
}
TODOListMain.java
import java.util.Scanner;
/* This class runs a console interface between a user and
* an instance of an EventSchedule.*/
public class TODOListMain {
//main method
public static void main(String[] args)
{
System.out.println("TODO List");
//define the scanner object
Scanner scan = new Scanner(System.in);
int initialSize = 5;
//define the class object
TODOList toDoList = new TODOList(initialSize);
//define the boolean variable
boolean keepGoing = true;
String userStr = "";
int position;
//Using while loop to print the menu
while(keepGoing) {
System.out.println("Main Menu:");
System.out.println("Enter A to add an item.");
System.out.println("Enter R to replace an item.");
System.out.println("Enter L to remove the last item.");
System.out.println("Enter P to print all item.");
System.out.println("Enter C to clear all items.");
System.out.println("Enter X to quit.");
System.out.println("");
userStr = scan.nextLine();
//If the user choice is A
if (userStr.equalsIgnoreCase("A")){
//Prompt and read the item
System.out.println("Enter the item: ");
userStr = scan.nextLine();
//call the method to add item in the list
toDoList.addItem(userStr);
}
//If the user choice is R
else if (userStr.equalsIgnoreCase("R")){
System.out.println("Enter the number of the item to be replaced:");
//Prompt and read the number in the list
position = Integer.parseInt(scan.nextLine());
//Prompt the replaced item
System.out.println("Enter the replacement item:");
//read the item
userStr = scan.nextLine();
//call the method to replace.If item is exist
if(toDoList.replaceItemAt(userStr, position))
System.out.println("Item replaced.");
//Otherwise item is not replcaed
else
System.out.println("Item not replaced- invalid number.");
}
//If the user input is L
else if (userStr.equalsIgnoreCase("L"))
{
//call the method to replace the item
if(toDoList.removeLastItem())
System.out.println("Last item removed.");
else
System.out.println("Item not removed- list empty.");
}
//If the user input is P
else if (userStr.equalsIgnoreCase("P"))
{
//call the method to print the items in the list
System.out.println("Your items: ");
System.out.println(toDoList.getToDoListAsString());
}
//If the input is C
else if (userStr.equalsIgnoreCase("C"))
{
//delete all items in the list
toDoList.clearToDoList();
System.out.println("Items cleared.");
}
//If the input is X,then set the boolean value to false
else if(userStr.equalsIgnoreCase("X"))
keepGoing = false;
else
System.out.println("Unrecognized input.");
}
//end the program
System.out.println("Bye for now.");
scan.close();
}
}
TODOListTest.java
import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.*;
public class TODOListTest {
private TODOList toDoList;
/** Fixture initialization (common initialization
* for all tests). **/
@Before public void setUp() {
toDoList = new TODOList(4);
}
/** Test for required instance variable declarations. **/
@Test
public void initialLengthNameTest() {
Field[] fields = TODOList.class.getDeclaredFields();
boolean wasDeclared = false;
for(int i=0;i<fields.length;i++){
if(fields[i].getName().equals("initialLength")){
wasDeclared = true;
}
}
assertEquals("Test 1: The instance variable initialLength has not been declared.", true, wasDeclared);
}
@Test
public void toDoListNameTest() {
Field[] fields = TODOList.class.getDeclaredFields();
boolean wasDeclared = false;
for(int i=0;i<fields.length;i++){
if(fields[i].getName().equals("toDoList")){
wasDeclared = true;
}
}
assertEquals("Test 2: The instance variable toDoList has not been declared.", true, wasDeclared);
}
@Test
public void numItemsNameTest() {
Field[] fields = TODOList.class.getDeclaredFields();
boolean wasDeclared = false;
for(int i=0;i<fields.length;i++){
if(fields[i].getName().equals("numItems")){
wasDeclared = true;
}
}
assertEquals("Test 3: The instance variable numItems has not been declared.", true, wasDeclared);
}
/** Test for required instance variable initializations in constructor. **/
@Test
public void initialLengthTypeTest() {
Field[] fields = TODOList.class.getDeclaredFields();
String varType = null;
for(int i=0;i<fields.length;i++){
if(fields[i].getName().equals("initialLength")){
varType = fields[i].getType().getName();
}
}
assertEquals("Test 4: The instance variable initialLength has not been declared as an int.", "int", varType);
}
@Test
public void toDoListTypeTest() {
Field[] fields = TODOList.class.getDeclaredFields();
String varType = null;
for(int i=0;i<fields.length;i++){
if(fields[i].getName().equals("toDoList")){
varType = fields[i].getType().getName();
}
}
assertEquals("Test 5: The instance variable toDoList has not been declared as an int.", "[Ljava.lang.String;", varType);
}
/** Test that the list has been created. **/
@Test
public void initListTest() {
String[] items = toDoList.getToDoList();
assertNotEquals("Test 6: The array is null- list may not have been initialized.", null, items);
}
/** Test the addItem method. **/
@Test
public void addOneItemTest() {
toDoList.addItem("walk the cat");
String[] items = toDoList.getToDoList();
assertEquals("Test 7: The item was not added.", "walk the cat", items[0]);
}
/** Test the addItem method-length of array. **/
@Test
public void addOneItemLenOneTest() {
toDoList.addItem("walk the cat");
String[] items = toDoList.getToDoList();
assertEquals("Test 8: Call to addItem- the list should contain one item.", 1, items.length);
}
/** Test the getNumberOfItems method on an empty list. **/
@Test
public void initListSizeTest() {
int len = toDoList.getNumberOfItems();
assertEquals("Test 9: The getNumberOfItems method should return 0 on an empty list.", 0, len);
}
/** Test the isEmpty method on an empty list. **/
@Test
public void initListIsEmptyTest() {
boolean empty = toDoList.isEmpty();
assertEquals("Test 10: The isEmpty method should return true on an empty list.", true, empty);
}
/** Test the getNumberOfItems method on a list with one item. **/
@Test
public void oneItemListSizeTest() {
toDoList.addItem("walk the cat");
int len = toDoList.getNumberOfItems();
assertEquals("Test 11: The getNumberOfItems method should return 1.", 1, len);
}
/** Test the replaceItemAt method. **/
@Test
public void replaceItemAtTest() {
toDoList.addItem("walk the cat");
toDoList.replaceItemAt("walk the dog", 1);
String[] items = toDoList.getToDoList();
assertEquals("Test 12: The item "walk the cat" at position 1 was not replaced with "walk the dog".", "walk the dog", items[0]);
}
/** Test the removeLastItem method. **/
@Test
public void removeLastItemTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.removeLastItem();
String[] items = toDoList.getToDoList();
assertEquals("Test 13: The last item should be: "eat Halloween candy".", "eat Halloween candy", items[items.length-1]);
}
/** Test the clearToDoList method. **/
@Test
public void clearItemsTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.clearToDoList();
String[] items = toDoList.getToDoList();
assertEquals("Test 14: After adding items then calling clearToDoList, the item list should be empty.", 0, items.length);
}
/** Test the getToDoListAsString method on an empty list. **/
@Test
public void initListGetItemStrTest() {
String listStr = toDoList.getToDoListAsString();
assertEquals("Test 15: The getItemStr method should return "no items" on an empty list.", "no items", listStr.trim());
}
/* Test private method expandList on empty list of length 5. */
@Test
public void expandListTest1()throws Exception {
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("expandList", new Class[]{String[].class});
methodToExecute.setAccessible(true);
String[] args = new String[5];
Object expandedListObj = methodToExecute.invoke(toDoList, new Object[]{args});
String[] expandedList = (String[])expandedListObj;
int result = expandedList.length;
assertEquals("Test 16: The expandList method did not create an array of double the length of the array passed in.", 10, result);
}
/* Test private method isFull on default list. */
@Test
public void isFullTest1()throws Exception {
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("isFull");
methodToExecute.setAccessible(true);
Boolean boolObj = (Boolean)methodToExecute.invoke(toDoList);
boolean result = boolObj.booleanValue();
assertEquals("Test 17: The isFull method should return false on an array with NULL values.", false, result);
}
/** Test the isEmpty method on a list with one item. **/
@Test
public void oneItemListIsEmptyTest() {
toDoList.addItem("walk the cat");
boolean empty = toDoList.isEmpty();
assertEquals("Test 18: The isEmpty method should return false on list with one item.", false, empty);
}
/** Test the addItem method-length of array. **/
@Test
public void addOneItemLenZeroTest() {
toDoList.addItem("walk the cat");
String[] items = toDoList.getToDoList();
assertNotEquals("Test 19: Call to addItem- the item was not added.", 0, items.length);
}
/** Test the getItemStr method on a list with one item. **/
@Test
public void oneItemListGetItemStrTest() {
toDoList.addItem("walk the cat");
String listStr = toDoList.getToDoListAsString();
assertEquals("Test 20: The getItemStr method should return "1 walk the cat".", "1 walk the cat", listStr.trim());
}
/* Remove the item and test getNumberOfItems. */
@Test
public void oneItemListRemoveLastSizeTest() {
toDoList.addItem("walk the cat");
toDoList.removeLastItem();
int len = toDoList.getNumberOfItems();
assertEquals("Test 21: The getNumberOfItems method should return 0 after adding and calling removeLastItem.", 0, len);
}
/* Remove the item and test isEmpty. */
@Test
public void oneItemListRemoveLastIsEmptyTest() {
toDoList.addItem("walk the cat");
toDoList.removeLastItem();
boolean empty = toDoList.isEmpty();
assertEquals("Test 22: The isEmpty method should return true after adding an item, then calling removeLastItem.", true, empty);
}
/** Test the getNumberOfItems method on populated list. **/
@Test
public void getNumberOfItemsAfterAddsTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
int len = toDoList.getNumberOfItems();
assertEquals("Test 23: After adding 4 items the size of the list should be 4.", 4, len);
}
/** Test the replaceItemAt for a first item. **/
@Test
public void replaceItemAtBeginTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.replaceItemAt("Fry burgers", 1);
String[] items = toDoList.getToDoList();
assertEquals("Test 24: The item "walk the cat" at position 1 was not replaced with "Fry burgers".", "Fry burgers", items[0]);
}
/** Test the replaceItemAt for a last item. **/
@Test
public void replaceItemAtEndTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.replaceItemAt("Fry burgers", 4);
String[] items = toDoList.getToDoList();
assertEquals("Test 25: The item eat Halloween candy at position 4 was not replaced with Fry burgers.", "Fry burgers", items[3]);
}
/** Test the replaceItemAt for a middle item. **/
@Test
public void replaceItemAtMiddleTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.replaceItemAt("Fry burgers", 3);
String[] items = toDoList.getToDoList();
assertEquals("Test 26: The item "eat Halloween candy" at position 3 was not replaced with "Fry burgers".", "Fry burgers", items[2]);
}
/** Test the replaceItemAt for a middle item returns true. **/
@Test
public void replaceItemAtMiddleReturnsTrueTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
boolean res = toDoList.replaceItemAt("Fry burgers", 2);
assertEquals("Test 27: Calling replaceElementAt on a valid index should return true.", true, res);
}
/** Test the replaceItemAt for a non-existent item returns false. **/
@Test
public void replaceItemAtInvalidIndexTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
boolean res = toDoList.replaceItemAt("Fry burgers", 5);
assertEquals("Test 28: Calling replaceElementAt on an index out of range should return false.", false, res);
}
/** Test the clearToDoList then isEmpty method. **/
@Test
public void clearMultipleItemsThenIsEmptyTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.clearToDoList();
boolean empty = toDoList.isEmpty();
assertEquals("Test 29: After adding items then calling clearToDoList, the isEmpty method should return true.", true, empty);
}
/** Test the clearToDoList then getNumberOfItems method. **/
@Test
public void clearMultipleItemsThenGetSizeTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.clearToDoList();
int len = toDoList.getNumberOfItems();
assertEquals("Test 30: After adding items then calling clearToDoList, the getNumberOfItems method should return 0.", 0, len);
}
/** Test the removeLast on list size 4. **/
@Test
public void removeLastOnList4Test() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.removeLastItem();
String[] items = toDoList.getToDoList();
assertEquals("Test 31: Testing removeLastItem: The last item should be "eat Halloween candy".", "eat Halloween candy", items[2]);
}
/** Test the removeLast until list is empty. **/
@Test
public void removeLastOnList4UntilEmptyTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.removeLastItem();
toDoList.removeLastItem();
toDoList.removeLastItem();
toDoList.removeLastItem();
String[] items = toDoList.getToDoList();
assertEquals("Test 32: Testing removeLastItem: The item list should be empty.", 0, items.length);
}
/** Test the removeLast returns true on non-empty list. **/
@Test
public void removeLastOnList4NonEmptyTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.removeLastItem();
toDoList.removeLastItem();
toDoList.removeLastItem();
boolean result = toDoList.removeLastItem();
assertEquals("Test 33: The call to removeLastItem should return true on a non-empty list.", true, result);
}
/** Test the removeLast after list is empty. **/
@Test
public void removeLastOnList4AfterEmptyTest() {
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
toDoList.addItem("eat Halloween candy");
toDoList.addItem("make dentist appointment");
toDoList.removeLastItem();
toDoList.removeLastItem();
toDoList.removeLastItem();
toDoList.removeLastItem();
boolean result = toDoList.removeLastItem();
assertEquals("Test 34: The call to removeLastItem should return false on an empty list.", false, result);
}
/* Test private method expandList on list with data. */
@Test
public void expandListTest2()throws Exception {
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("expandList", new Class[]{String[].class});
methodToExecute.setAccessible(true);
String[] args = {"walk the cat", "walk the dog", "eat Halloween candy", "make dentist appointment"};
Object expandedListObj = methodToExecute.invoke(toDoList, new Object[]{args});
String[] expandedList = (String[])expandedListObj;
String result = expandedList[0];
assertEquals("Test 35: The expandList method did not correctly copy the data from the array passed in.", "walk the cat", result);
}
/* Test private method expandList on list with data. */
@Test
public void expandListTest3()throws Exception {
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("expandList", new Class[]{String[].class});
methodToExecute.setAccessible(true);
String[] args = {"walk the cat", "walk the dog", "eat Halloween candy", "make dentist appointment"};
Object expandedListObj = methodToExecute.invoke(toDoList, new Object[]{args});
String[] expandedList = (String[])expandedListObj;
String result = expandedList[3];
assertEquals("Test 36: The expandList method did not correctly copy the data from the array passed in.", "make dentist appointment", result);
}
/* Test private method expandList on list with data. */
@Test
public void expandListTest4()throws Exception {
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("expandList", new Class[]{String[].class});
methodToExecute.setAccessible(true);
String[] args = {"walk the cat", "walk the dog", "eat Halloween candy", "make dentist appointment"};
Object expandedListObj = methodToExecute.invoke(toDoList, new Object[]{args});
String[] expandedList = (String[])expandedListObj;
String result = expandedList[4];
assertEquals("Test 37: The expandList method did not correctly copy the data from the array passed in.", null, result);
}
/* Test private method isFull after adding one item. */
@Test
public void isFullTest2()throws Exception {
toDoList = new TODOList(2);
toDoList.addItem("walk the cat");
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("isFull");
methodToExecute.setAccessible(true);
Boolean boolObj = (Boolean)methodToExecute.invoke(toDoList);
boolean result = boolObj.booleanValue();
assertEquals("Test 38: The isFull method should return false on an array with NULL values.", false, result);
}
/* Test private method isFull on full list. */
@Test
public void isFullTest3()throws Exception {
toDoList = new TODOList(2);
toDoList.addItem("walk the cat");
toDoList.addItem("walk the dog");
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("isFull");
methodToExecute.setAccessible(true);
Boolean boolObj = (Boolean)methodToExecute.invoke(toDoList);
boolean result = boolObj.booleanValue();
assertEquals("Test 39: The isFull method should return true on an array without NULL values.", true, result);
}
/** Test that the list has been initialized in constructor. **/
@Test
public void initListConstructorTest2() throws Exception{
int randLen = (int)(Math.random()*6+1);
toDoList = new TODOList(randLen);
for(int i=0;i<randLen;i++)
toDoList.addItem("walk the cat");
Class classToCall = Class.forName("TODOList");
Method methodToExecute = classToCall.getDeclaredMethod("isFull");
methodToExecute.setAccessible(true);
Boolean boolObj = (Boolean)methodToExecute.invoke(toDoList);
boolean result = boolObj.booleanValue();
assertEquals("Test 40: The item list length may not have been initialized in the constructor.", true, result);
}
/** Test that the list will be expanded. **/
@Test
public void listExpandsTest()throws Exception {
toDoList = new TODOList(2);
toDoList.addItem("eat");
toDoList.addItem("sleep");
toDoList.addItem("work");
String[] items = toDoList.getToDoList();
assertEquals("Test 41: Initial length of 2- added three items. Length of list should now be three.", 3, items.length);
}
}
Explanation / Answer
Have made changes in the TODOList.java file to call expandList method when the TODO list is full, and then add the item at the end. The changes have been highlighted in bold. Please try the below given code for TODOList.java
// TODOList.java
/* This class encapsulates a list of user-defined items that should be done- a "TODO" list.
* Each item on the list is represented by a String object.
* The list is implemented by a String array. The array is initialized in the constructor to an
* initial length that is passed to the constructor. The initial array contains only NULL values.
* A user adds an item (a String) to the list by calling the addItem method, passing in a String
* that represents the to-do item.
* Thus, the array may have fewer items (Strings) than its length.
*
* For example, assume the list has an initial length of 5. It looks like this:
* NULL, NULL, NULL, NULL, NULL
*
* Then, a user adds three items. It looks like this:
* "eat lunch", "walk dog", "study Java", NULL, NULL
*
* The length of the list is 5, the number of items is 3. The NULL values are unoccupied cells.
* The capacity of the array is its length. The size of the data stored in the array is less than
* or equal to its capacity.
*
* If a user wants to add more items to a list that has no more NULL values, i.e. no more room,
* the expandArray method is called to double the length of the toDoList. The original Strings
* are in the same positions, but the new array has double the capacity- more room for adding items.
*/
public class TODOList {
/* YOUR Instance variable declarations here. */
private String[] TODO;
private int initialLength;
private int numItems;
/* Constructor that initializes the initialLength variable to the value passed in.
* It also initializes the toDoList with the initial length.
* Any other instance variables may be initialized as well.
*/
public TODOList(int initialLen)
{
this.initialLength = initialLen;
this.TODO = new String[initialLen];
this.numItems = 0;
}
/* Add the item passed in to the end of the list.
* For example, if the toDoList list contained: "eat lunch", "walk dog",
* the next item added, "study Java", would result in this list:
* "eat lunch", "walk dog", "study Java"
* Suggestion: use instance variable to keep track of the index of the next available cell.
*/
public void addItem(String itemStr)
{
if(!isFull()) // if TODO list is not empty , then add the item at the last
{
TODO[numItems] = itemStr;
numItems += 1;
}else // else expand the list and add the item at the last
{
TODO = expandList(TODO);
TODO[numItems] = itemStr;
numItems += 1;
}
}
/* Overwrite the item at "position" to be the parameter "itemStr".
* Note: position is a positive integer > 0 that has to be a valid position
* in the toDoList. A valid position corresponds to an item stored in the
* toDoList. For example, if this was the list:
1 walk the cat
2 order doughnuts
3 go to the gym
4 wash dishes
* valid positions would be 1, 2, 3, 4. All other integers are invalid.
* This method returns true if a valid position was passed in, false otherwise.
*/
public boolean replaceItemAt(String itemStr, int position)
{
if (position > 0 && position <= initialLength && TODO[position - 1] != null)
{
TODO[position - 1] = itemStr;
return true;
}
return false;
}
/* Remove the last item in the toDoList.
* For example, if the toDoList list contained: "eat lunch", "walk dog", "study Java",
* removing the last item would result in this list:
* "eat lunch", "walk dog".
* This method returns true if there is at least one item in the list,
* false otherwise.
*/
public boolean removeLastItem()
{
if (initialLength > 0 && numItems > 0)
{
numItems -= 1;
TODO[numItems] = null;
return true;
}
return false;
}
/*
* Return a list that contains only the items that have been added.
* This list does not contain any NULL values.
* For example, if the toDoList list contained: "eat lunch", "walk dog", "study Java", NULL, NULL
* This method would return this array: "eat lunch", "walk dog", "study Java"
* If the toDoList does not contain any items, this method returns a String array with zero length.
*/
public String[] getToDoList()
{
int numLoop = 0;
String[] result = new String[numItems];
while (numLoop < initialLength && TODO[numLoop] != null)
{
result[numLoop] = TODO[numLoop];
numLoop++;
}
return result;
}
/* Remove all items from the list, resulting in an empty list.
* The capacity of the list returns to the initial length.*/
public void clearToDoList()
{
int numLoop = 0;
while (numLoop < TODO.length && TODO[numLoop] != null)
{
TODO[numLoop] = null;
numItems -= 1;
numLoop++;
}
}
/* Returns a String representation of the current item list according to
* these specifications:
* Each item is on one line, position number first followed by one blank,
* followed by the item String.
* For example:
1 walk the cat
2 order doughnuts
3 go to the gym
4 wash dishes
* If no items are on the list the String returned is: "no items".*/
public String getToDoListAsString()
{
int numItems = 0;
String result = "";
if (TODO[0] == null)
{
result = "no items";
return result;
}
// loop till the end of TODO list and last non-null item
while (numItems < TODO.length && TODO[numItems] != null) {
result = result +" " + TODO[numItems];
numItems++;
}
return result;
}
/* Returns the number of items stored in the item list.*/
public int getNumberOfItems(){
return numItems;
}
/* Returns true if the item list contains no items, false otherwise.*/
public boolean isEmpty(){
if (numItems > 0)
{
return false;
}
return true;
}
/****** Private, "helper" method section ******/
/* Creates a new array that is double the size of the array passed in, copies the data
* from that array to the new array, and returns the new array.
* Note that the new array will contain the items
*from the previous array followed by NULL values.*/
private String[] expandList(String[] inputList)
{
String[] newArray = new String[inputList.length * 2];
int numLoop = 0;
while (numLoop < inputList.length && inputList[numLoop] != null) {
newArray[numLoop] = inputList[numLoop];
numLoop++;
}
return newArray;
}
/* A full item list is an array where all cells contain an item. That
* means there is no cell that contains NULL.
* This method returns true if all cells in the array contain a String
* object, false otherwise.
*/
private boolean isFull()
{
if (numItems == TODO.length)
{
return true;
}
return false;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.