[Solved] how do I initialize 0 to both constructors? [closed]


Your code is correct for your teacher’s requirements so far. Constructors effectively create an Object. In this case you have 2 constructors VendingMachine() and VendingMachine(int cans) both of which in their respective code initialize tokenCount to 0.

Walking through your Tester line by line

VendingMachine machine = new VendingMachine();

This constructor creates a new VendingMachine called machine with canCount of 10 and tokenCount of 0. As you can see here your tokenCount is 0 it only changes later when you call machine.insertToken().

machine.add(10);

This “adds” 10 cans to machine making the canCount now 20. tokenCount is still at 0

boolean status;

This creates a local variable called status.

machine.insertToken();

This “inserts” a “token” which turns the canCount to 19 and tokenCount to 1.

status = machine.insertToken();

This “inserts” a “token” and stores true to status and turns canCount to 18 and tokenCount to 2.

Naturally your tokenCount is going to be 2 because you called insertToken() twice. However you need to change your expected output for can count or remove the add(10). This is rather trivial programming. I would consider looking into how to use the debugger as it really helps see what your code is doing behind the scenes.

2

solved how do I initialize 0 to both constructors? [closed]