I ran this code for each test. Test 1, and test 2 work but not test 3 because I
ID: 3712922 • Letter: I
Question
I ran this code for each test. Test 1, and test 2 work but not test 3 because I have to modify this method.
Specification: LetterInventorysubtract(LetterInventory other) "Constructs and returns a new LetterInventory object that represents the result of subtracting the other inventory from this inventory (i.e., subtracting the counts in the other inventory from this object’s counts). If any resulting count would be negative, your method should return null. The two LetterInventoryobjects being subtracted (this and other) should not be changed by this method
public LetterInventory subtract(LetterInventory other) {
LetterInventory inventory2 = new LetterInventory(this.toString() );
for (int i = 0; i < count.length; i++) {
inventory2.count[i] = inventory2.count[i] - other.count[i];
if (inventory2.count[i] < 0) {
return null;
}
}
return inventory2;
}
}
console output :
Testing these two strings:
i1: "aaggghhhh"
i2: "ggg"
constructing i1 and i2
constructing and testing i1.add(i2)
inventory = [aagggggghhhh]
toString, size, isEmpty, and count all passed
constructing and testing i2.add(i1)
inventory = [aagggggghhhh]
toString, size, isEmpty, and count all passed
constructing and testing i1.subtract(i2)
inventory = [aahhhh]
size failed
correct size = 6
your size = 9
Explanation / Answer
public LetterInventory subtract(LetterInventory other) {
// Create a new inventory which is to be returned
LetterInventory inventory2 = new LetterInventory("");
// Iterate loop over count array
for (int i = 0; i < count.length; i++) {
// Set count[i] for inventory2 equals to
// this.count[i]- count[i] for other
inventory2.count[i] = this.count[i] - other.count[i];
// If subtraction is negative, return null
if (inventory2.count[i] < 0) {
return null;
}
// Add count[i], to size
inventory2.size += inventory2.count[i];
}
// Return new inventory after for loop
return inventory2;
}