{"record":{"id":"0a4242b6d77884a0","repo":"TheAlgorithms/Java","slug":"input-string-must-be-a-valid-integer-s","errorCode":null,"errorMessage":"Input string must be a valid integer: {s}","messagePattern":"Input string must be a valid integer: (.+?)","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/maths/HarshadNumber.java","lineNumber":64,"sourceCode":"     * digits.\n     *\n     * @param s the string representation of the number to be checked\n     * @return {@code true} if the number is a Harshad number, otherwise\n     *         {@code false}\n     * @throws IllegalArgumentException if {@code s} is null, empty, or represents a\n     *                                  non-positive integer\n     * @throws NumberFormatException    if {@code s} cannot be parsed as a long\n     */\n    public static boolean isHarshad(String s) {\n        if (s == null || s.isEmpty()) {\n            throw new IllegalArgumentException(\"Input string cannot be null or empty\");\n        }\n\n        final long n;\n        try {\n            n = Long.parseLong(s);\n        } catch (NumberFormatException e) {\n            throw new IllegalArgumentException(\"Input string must be a valid integer: \" + s, e);\n        }\n\n        if (n <= 0) {\n            throw new IllegalArgumentException(\"Input must be a positive integer. Received: \" + n);\n        }\n\n        int sumOfDigits = 0;\n        for (char ch : s.toCharArray()) {\n            if (Character.isDigit(ch)) {\n                sumOfDigits += ch - '0';\n            }\n        }\n\n        return n % sumOfDigits == 0;\n    }\n}\n","sourceCodeStart":46,"sourceCodeEnd":81,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/HarshadNumber.java#L46-L81","documentation":"Thrown by HarshadNumber.isHarshad(String s) when Long.parseLong(s) throws a NumberFormatException. The method wraps the parse in a try-catch and re-throws as IllegalArgumentException with the original string and the original exception as cause. This covers any string that is non-empty but not a valid long literal: non-numeric characters, decimals, overflow, or malformed signs.","triggerScenarios":"Calling isHarshad(\"abc\"), isHarshad(\"3.14\"), isHarshad(\"12abc\"), isHarshad(\"999999999999999999999999\") (exceeds Long.MAX_VALUE), isHarshad(\" 5\") (leading space), or isHarshad(\"+\") (sign with no digits). Note: Long.parseLong does NOT trim, so leading/trailing spaces fail.","commonSituations":"User input from text fields or CLI arguments without sanitization. Data from CSV/JSON files with mixed-type columns. Locale-specific number formatting (commas as thousand separators) that parseLong rejects.","solutions":["Sanitize the string before calling: trim whitespace and validate it matches a numeric pattern (e.g., s.trim().matches(\"-?\\\\d+\")).","If the input may contain commas or other formatting, strip or parse it with NumberFormat first, then convert to string.","Validate against Long range to avoid overflow: check digit count or use BigInteger for pre-validation."],"exampleFix":"// before\nboolean result = HarshadNumber.isHarshad(rawInput);\n\n// after\nString cleaned = rawInput == null ? \"\" : rawInput.trim();\nif (!cleaned.matches(\"-?\\\\d+\")) {\n    throw new IllegalArgumentException(\"Not a valid integer: \" + rawInput);\n}\nboolean result = HarshadNumber.isHarshad(cleaned);","handlingStrategy":"validation","validationCode":"String cleaned = s == null ? \"\" : s.trim();\nif (!cleaned.matches(\"-?\\\\d+\")) {\n    throw new IllegalArgumentException(\"Not a valid integer: \" + s);\n}\nboolean result = HarshadNumber.isHarshad(cleaned);","typeGuard":"static boolean isParseableLong(String s) {\n    return s != null && !s.isEmpty() && s.trim().matches(\"-?\\\\d+\");\n}","tryCatchPattern":"try {\n    boolean result = HarshadNumber.isHarshad(s);\n} catch (IllegalArgumentException e) {\n    if (e.getCause() instanceof NumberFormatException) {\n        // parse failure; input is not a valid integer\n    }\n}","preventionTips":["Trim and validate the string matches a numeric pattern before calling.","Strip locale-specific formatting (commas, spaces) before parsing.","Check against Long range for very long digit strings."],"tags":["math","harshad","string-parsing","number-format","argument-validation"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}