019-003-009
Multi-Catch Input Parser
Hard
Problem Description
Multi-Catch Input Parser
In this problem: You will create an InputParser class that converts user input strings into different types, and handle NumberFormatException, ArrayIndexOutOfBoundsException, and IllegalArgumentException that can occur in the parseAndProcess(String input) method using multi-catch syntax.
Learning Objective: Efficiently catch multiple exceptions using multi-catch syntax and understand how catch block ordering affects execution results
Overview
The InputParser class parses comma-separated input strings, converts the element at a specified index to an integer, and processes it. When the input is invalid, appropriate exceptions are thrown.
Specifications
InputParser Class (InputParser.java)
- Define a
parseAndProcess(String input)method- Parameter: comma-separated string (format:
"value1,value2,value3,...:index") - Split the string by colon (
:), interpret the first part as the value array and the second part as the index - If input is
nullor empty, throwIllegalArgumentException(message:"Input must not be null or empty") - If no colon is present, throw
IllegalArgumentException(message:"Input must contain ':' separator") - If the index part cannot be converted to an integer,
NumberFormatExceptionoccurs - If the index is out of array bounds,
ArrayIndexOutOfBoundsExceptionoccurs - On success, convert the value at the specified index to an integer and return
"Parsed value: number"
- Parameter: comma-separated string (format:
Main Class (Main.java)
- Test 4 input patterns:
- Valid input:
"10,20,30:1"- display value - Number format error:
"10,abc,30:1"- catch NumberFormatException - Index out of bounds:
"10,20,30:5"- catch ArrayIndexOutOfBoundsException - Invalid input:
""- catch IllegalArgumentException
- Valid input:
- Use try-catch for each test, implementing multi-catch (
NumberFormatException | ArrayIndexOutOfBoundsException) and proper catch ordering
Output Format
--- Test 1: Valid input ---
Result: Parsed value: 20
--- Test 2: Number format error ---
Caught NumberFormatException | ArrayIndexOutOfBoundsException: For input string: "abc"
--- Test 3: Index out of bounds ---
Caught NumberFormatException | ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
--- Test 4: Invalid input ---
Caught IllegalArgumentException: Input must not be null or empty
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up