A stapler staples; it doesn't talk but more important is that your logic is flakey
here and there. A new stapler contains 100 staples. If it contains, say 40 staples
I can add 60 more staples; more simply don't fit. It is quite easy to translate these
notions to Java code:
-
public class Stapler {
-
public static final int MAXSTAPLES= 100;
-
private int staples= MAXSTAPLES; // init at construction time
-
//
-
// not really needed constructor:
-
public Stapler() { } // do nothing
-
...
-
}
This is the first skeleton of the Stapler class: it contains 100 staples. Now add
a 'staple' method; it can staple one staple if it contains staples; it returns true
if it succeeded and false if it was empty:
-
public boolean staple() {
-
if (staples > 0) {
-
staples--;
-
return true;
-
}
-
return false;
-
}
Note that it doesn't say anything, i.e. it just staples and returns whether or not
it had succeeded. An overloaded method that staples n times could look like this:
-
public int staple(int n) { // staple n staples
-
while (n > 0 && staple()) { // protect against nonsense values
-
staple(); // staple once
-
n--;
-
}
-
return n; // return the number of staples to do
-
}
Refilling the stapler takes a bit of 101 math: when it has x <= 100 staples left
you can add 100-x more staples to it. Suppose we can't remove staples from
the stapler:
-
public int refill(int n) { // try to add n staples to the stapler
-
if (n > 0) { // protect against nonsense values
-
int newStaples= Math.min(staples+n, MAXSTAPLES);
-
n-= newStaples-staples; // those didn't fit
-
staples= newStaples; // refill the stapler
-
}
-
return n; // return number of staples that couldn't be added
-
}
You can poop up this little class a bit more by adding a getter method. You can
extend this class by a TalkingStapler that indeed tells what it's doing (that'd be
a bit of a silly stapler if you'd ask me, but feel free to add whatever you want).
kind regards,
Jos