Vending Machine – Part 2
A "bulletproof" application is free of bugs and doesn't fail/crash no matter what. The key is to
-
catch checked exceptions (outside the application's control).
-
fix unchecked exceptions (resulting from badly written code).
There aren't any checked exceptions. So, your primary focus is to fix unchecked exceptions.
Task 1 – InputMismatchException
Thrown by
Scanner
if the user enters a value that it wasn't expecting.
You need to prevent the application from crashing. An unchecked exception implies there's something wrong/missing in your code.
The starter code crashes if the user enters a type mismatch.
If one of the user inputs is invalid, you need to:
-
println
:"INVALID INPUT."
-
restart the
while
loop.
SUGGESTION: Use the conditional assignment syntax (?
and :
). Having three if-else
statements can make the code long and messy.
Expected Output:
Task 2 – ArrayIndexOutOfBoundsException
Thrown if you index outside the bounds of the array.
If the user enters an index that's out of range, the application will crash.
You can't let the application crash. If the index is out of bounds:
-
println
:"INVALID RANGE"
-
restart the
while
loop.
Don't use the array from main()
. Define two methods in the Machine
class named getLength()
, getRowLength()
and call them. Then, test your condition by entering faulty values.
Expected Output:
Task 3 – IllegalArgumentException
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
If the user purchases the Berry, the dispense is successful. But if the user purchases the drink a second time, the application throws an IllegalArgumentException
.
If the user tries to buy a drink from an empty slot:
-
println
:"EMPTY SLOT"
. -
restart the
while
loop.
Expected Output:
Your code is now bulletproof!
No matter what the user throws at you, the application is free of bugs and will never crash. It can process any input and respond with grace.