To complete Challenge 34, the following code must be pasted into BlueJ™’s TaskManager class:
/**
* Checks for invalid index values
*
* @param n integer of index where task resides in ArrayList
*/
public boolean checkValidIndex(int n)
{
if (n >= 0)
return true;
else
return false;
}
Pasting this code into BlueJ™ will produce the same scenario as in your original blog post.
−Phoenix
This method does indeed catch any index values being passed in that are less than zero.
ReplyDeleteExtend the functionality to cover cases where the index passed in is out of bounds compared to the number of elements in the ArrayList.
For instance, if the ArrayList has 5 elements, and I pass in an index value of 5, the program will crash, throwing an IndexOutOfBounds exception.
To solve Challenge 34, a variety of code needs to be entered. First, one must add the following statement to the list of instance variables:
ReplyDeleteint size = -1;
Next, change the method “addTask” as such:
public int addTask(Task t)
{
tasks.add(t);
return size = size + 1;
}
After that, modify the method “removeTask” in a similar way:
public int removeTask(int n)
{
if (checkValidIndex(n))
{
tasks.remove(n);
size = size - 1;
}
else
System.out.print("ERROR: Cannot remove task with that index");
return size;
Finally, one must change the “if” statement in the “checkValidIndex” method so that it reads:
if (n >= 0 && size >= n)
This will produce the additional changes that you have asked for.
−Phoenix
This will work, but see if you can design this solution without using an integer to track size. All ArrayLists' have a property that can be utilized for this context.
ReplyDeleteThe far simpler solution to this problem is to simply change the original “if” statement in the “checkValidIndex” command to say the following:
ReplyDeleteif (n >= 0 && n <= tasks.size() - 1)
This will prevent “int” values that are too high or too low.
−Phoenix
Perfection. 70 XPs awarded.
ReplyDelete