Validate positive input

Validate positive input

Easy Java Exceptions 24 views
Explanation Complexity

Problem Statement

Task: if x is negative, throw IllegalArgumentException. Else return x.

Input Format

An integer x.

Output Format

If x is negative → throw IllegalArgumentException
Else → return x.

Example

-5
IllegalArgumentException

Constraints

• x is an integer

• Must manually check condition

Concept Explanation

If value is negative, it is considered invalid.
So we throw IllegalArgumentException.
Otherwise, we simply return the value.

Step-by-Step Explanation

1.Read integer x.

2.If x < 0:

• Throw new IllegalArgumentException("Negative value not allowed").

3.Else:

• Return x.

This validates input and throws exception if value is negative in Java.

Concept Explanation

If value is negative, it is considered invalid.
So we throw IllegalArgumentException.
Otherwise, we simply return the value.

Step-by-Step Explanation

1.Read integer x.

2.If x < 0:

• Throw new IllegalArgumentException("Negative value not allowed").

3.Else:

• Return x.

This validates input and throws exception if value is negative in Java.

Input / Output Format

Input Format
An integer x.
Output Format
If x is negative → throw IllegalArgumentException
Else → return x.
Constraints
• x is an integer

• Must manually check condition

Examples

Input:
-5
Output:
IllegalArgumentException

Example Solution (Public)

Java
static int requireNonNegative(int x){if(x<0) throw new IllegalArgumentException();return x;}

Official Solution Code

static int requireNonNegative(int x){if(x<0) throw new IllegalArgumentException();return x;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.