Here is an example solution:
public void removeFromBag(int toBeRemoved)
{
bagVals[toBeRemoved]--;
}
To remove from the bag, we decrease the count for the digit by one. Notice how similar this is to the addToBag method. A longer version (perhaps more readable) might look like this:
bagVals[toBeRemoved] = bagVals[toBeRemoved] - 1;
// to remove all of a digit from the bag, we set the digit's count to zero
public void removeAllFromBag(int toBeRemoved)
{
bagVals[toBeRemoved] = 0;
}
To empty the bag, we set all digits' counts to zero by setting each digit count to zero:
public void emptyBag()
{
for (int i = 0; i < bagVals.length; i++)
{
bagVals[i] = 0;
}
}
This method could also have made use of the removeAllFromBag method above, e.g.:
public void emptyBag()
{
for (int i = 0; i < bagVals.length; i++)
{
removeAllFromBag(i);
}
}
It is often preferable to make use of methods defined within the class to improve maintainability of the code.
//print out the number of each digit present in the bag
public void printCounts()
{
for (int i = 0; i < bagVals.length; i++)
{
System.out.print(findNum(i) + " ");
//Instead of using findNum, we could also have written
//System.out.print (bagVals[i] + " ");
}
// one way to print a line separator
System.out.println();
}