Write a register(name, email, age) method that throws IllegalArgumentException with a precise message for each invalid field; try several sign-ups and print the results.
Solution
Main.java
public class Main {
static String register(String name, String email, String ageText) {
if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
if (!email.matches("[\\w.+-]+@[\\w-]+\\.[a-z]{2,}")) throw new IllegalArgumentException("invalid email '" + email + "'");
int age;
try {
age = Integer.parseInt(ageText);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("age must be a whole number", e);
}
if (age < 13) throw new IllegalArgumentException("must be at least 13, got " + age);
return "welcome " + name.strip() + " (" + age + ")";
}
public static void main(String[] args) {
String[][] forms = {{"Asha", "asha@mail.com", "21"}, {" ", "x@y.in", "30"}, {"Ravi", "ravi@mail", "25"}, {"Meena", "meena@lf.in", "twelve"}, {"Kid", "kid@lf.in", "9"}};
for (String[] f : forms) {
try {
System.out.println(register(f[0], f[1], f[2]));
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
}
Output Verified by compiling and running
welcome Asha (21)
rejected: name is required
rejected: invalid email 'ravi@mail'
rejected: age must be a whole number
rejected: must be at least 13, got 9
IllegalArgumentException is the standard choice for invalid arguments; the NumberFormatException is kept as the cause.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!