Parse int with fallback

Parse int with fallback

Easy Java Exceptions 26 views
Explanation Complexity

Problem Statement

Task: parse integer from string; if invalid, return fallback value.

Input Format

• First line: A String s

• Second line: An integer fallback

Output Format

• Print one integer:

• Parsed integer if the string is valid

• Otherwise, fallback value

Example

12a3
50
123

Constraints

• -10^9 ≤ parsed integer ≤ 10^9

• -10^9 ≤ fallback ≤ 10^9

• 0 ≤ length of string ≤ 100

Concept Explanation

The string "12a3" contains a letter (a).
So it is not a valid integer.
Therefore, we return the fallback value.

Step-by-Step Explanation

• Read string s using Scanner.

• Read integer fallback.

• Use Integer.parseInt(s) inside a try block.

• If parsing is successful, print the parsed value.

• If NumberFormatException occurs, print the fallback value.

Concept Explanation

The string "12a3" contains a letter (a).
So it is not a valid integer.
Therefore, we return the fallback value.

Step-by-Step Explanation

• Read string s using Scanner.

• Read integer fallback.

• Use Integer.parseInt(s) inside a try block.

• If parsing is successful, print the parsed value.

• If NumberFormatException occurs, print the fallback value.

Input / Output Format

Input Format
• First line: A String s

• Second line: An integer fallback
Output Format
• Print one integer:

• Parsed integer if the string is valid

• Otherwise, fallback value
Constraints
• -10^9 ≤ parsed integer ≤ 10^9

• -10^9 ≤ fallback ≤ 10^9

• 0 ≤ length of string ≤ 100

Examples

Input:
12a3 50
Output:
123

Example Solution (Public)

Java
static int parseOrDefault(String s,int fallback){try{return Integer.parseInt(s);}catch(NumberFormatException e){return fallback;}}

Official Solution Code

static int parseOrDefault(String s,int fallback){try{return Integer.parseInt(s);}catch(NumberFormatException e){return fallback;}}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.