Page 1 of 1

[HD-OCP17/21-Fundamentals Pg 0, Sec. 12.8.0 - exercise]

Posted: Tue Nov 26, 2024 8:13 pm
by joaoclopes
Hello! Regarding the 5. do I have a better way to solve it than this?

Code: Select all

// Switch statement without pattern matching
if (obj instanceof String) {
    String str = (String) obj;
    switch (str.charAt(0)) {
        case 'a':
            iVal = 96;
            break;
        case 'A':
            iVal = 65;
            break;
        default:
            iVal = 0;
    }
} else {
    iVal = 0;
}

// Switch statement with pattern matching
switch (obj) {
    case String value
            when value.startsWith("a") -> iVal = 96;
    case String value
            when value.startsWith("A") -> iVal = 65;
    default -> iVal = 0;
}

// Switch expression without pattern matching
if (obj instanceof String) {
    String str = (String) obj;
    iVal = switch (str.charAt(0)) {
        case 'a' -> 96;
        case 'A' -> 65;
        default -> 0;
    };
} else {
    iVal = 0;
}

// Switch expression with pattern matching
iVal = switch (obj) {
    case String value
            when value.startsWith("a") -> 96;
    case String value
            when value.startsWith("A") -> 65;
    default -> 0;
};
Thanks!
João

Re: [HD-OCP17/21-Fundamentals Pg 0, Sec. 12.8.0 - exercise]

Posted: Sat Nov 30, 2024 9:30 pm
by admin
Sorry for the late reply. That's good solution. Good job :thumbup:

Re: [HD-OCP17/21-Fundamentals Pg 0, Sec. 12.8.0 - exercise]

Posted: Sun Dec 01, 2024 7:07 am
by joaoclopes
No problem! Thanks for the feedback! :thumbup: