← Back to Week 3 Hub
Workbook 3a — Exercise

Famous Quotes

Pick a quote by number — then harden the program so a bad number doesn't crash it  |  Workbook p.9

The Exercise

Create a Java app called famous-quotes. Store 10 of your favorite quotes in a String array. Ask the user to pick a number from 1 to 10 and display the matching quote.

First, run it with a valid number and see it work. Then run it again with a number like 12 and watch it crash. Your job is to wrap the array access in a try/catch so the program shows a friendly message instead of a stack trace.

Bonus: Loop back and let the user pick again until they choose to quit. Another bonus: add an option that picks a random quote.

Example Runs
Run 1 — Valid number
Pick a quote number (1-10): 3

"The only way to do great work is to love what you do."
Run 2 — Out of range, before try/catch
Pick a quote number (1-10): 12

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 10
at FamousQuotes.main(FamousQuotes.java:18)
Run 3 — Out of range, after try/catch
Pick a quote number (1-10): 12

That number is out of range. Try again.

Pick a quote number (1-10): 7

"In the middle of every difficulty lies opportunity."
Concepts You'll Use
Flow
Build 10-quote array
Prompt 1-10
Read int
try/catch access
Print quote or message
Loop again (bonus)

Workbook 3a, p.9 — Exercise: Famous Quotes

Bedtime Stories →