Dealership Workbook – Part 2
A "bulletproof" application is free of bugs and doesn't fail/crash no matter what. The key is to:
catchchecked exceptions (outside the application's control).
fix unchecked exceptions (resulting from badly written code).
You already caught the checked exceptions. Now, you will fix unchecked exceptions.
Task 1 –
Scannerif the user enters a value that it wasn't expecting.
You need to prevent the application from crashing. An unchecked exception implies that there's something wrong/missing in your code.
If you run the starter code, it prompts the user to enter a spot:
But if the user enters a type mismatch, the application crashes.
In the event of a type mismatch: you need to:
pick up the mismatch using
Task 2 – Fix the bug
A bug is code that doesn't behave the way it's supposed to.
If you enter a valid number (0 or 1) followed by a mismatch, your app will present a bug:
Your task is to fix the bug. Use breakpoints to visualize the runtime and identify the bug.
Hint: the bug is the classic '
Task 3 –
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:
"Please choose a valid parking spot."
Don't use the array from
main() to get the length. Define a method in
getLength() and call it from
main(). Then, test your condition by entering spots of -1, 2, and 5.
Task 4 –
Thrown if you try to access something (dot syntax) from a
If the user tries to buy a car from an empty spot, the application throws a
If the user tries to buy a car from an empty spot:
println("Spot " + <spot> + " is empty.")
Hint: You'll need to fix the getter in
Dealership.java. Use the conditional assignment syntax (ternary operators
: ) in place of
Task 5 – Check if the user wants to continue.
At the end of the
while loop, ask the user:
yes" to continue shopping.
If they type anything else,
Task 6 –
If you haven't already, add an
isEmpty() method to the Dealership class.
/** * Name: isEmpty * * @return (boolean) * Inside the function: * - return true if there are no more cars. * - return false otherwise. * */
isEmpty method from
main(). If the result is
We're all sold out!".
Task 7 –
scan.close() is now reachable. You can uncomment it.
The application 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 gracefully.