TheAlgorithms/Java · error · IllegalArgumentException

Input string must be a valid integer: {s}

Error message

Input string must be a valid integer: {s}

What it means

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.

Source

Thrown at src/main/java/com/thealgorithms/maths/HarshadNumber.java:64

     * digits.
     *
     * @param s the string representation of the number to be checked
     * @return {@code true} if the number is a Harshad number, otherwise
     *         {@code false}
     * @throws IllegalArgumentException if {@code s} is null, empty, or represents a
     *                                  non-positive integer
     * @throws NumberFormatException    if {@code s} cannot be parsed as a long
     */
    public static boolean isHarshad(String s) {
        if (s == null || s.isEmpty()) {
            throw new IllegalArgumentException("Input string cannot be null or empty");
        }

        final long n;
        try {
            n = Long.parseLong(s);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Input string must be a valid integer: " + s, e);
        }

        if (n <= 0) {
            throw new IllegalArgumentException("Input must be a positive integer. Received: " + n);
        }

        int sumOfDigits = 0;
        for (char ch : s.toCharArray()) {
            if (Character.isDigit(ch)) {
                sumOfDigits += ch - '0';
            }
        }

        return n % sumOfDigits == 0;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Sanitize the string before calling: trim whitespace and validate it matches a numeric pattern (e.g., s.trim().matches("-?\\d+")).
  2. If the input may contain commas or other formatting, strip or parse it with NumberFormat first, then convert to string.
  3. Validate against Long range to avoid overflow: check digit count or use BigInteger for pre-validation.

Example fix

// before
boolean result = HarshadNumber.isHarshad(rawInput);

// after
String cleaned = rawInput == null ? "" : rawInput.trim();
if (!cleaned.matches("-?\\d+")) {
    throw new IllegalArgumentException("Not a valid integer: " + rawInput);
}
boolean result = HarshadNumber.isHarshad(cleaned);
Defensive patterns

Strategy: validation

Validate before calling

String cleaned = s == null ? "" : s.trim();
if (!cleaned.matches("-?\\d+")) {
    throw new IllegalArgumentException("Not a valid integer: " + s);
}
boolean result = HarshadNumber.isHarshad(cleaned);

Type guard

static boolean isParseableLong(String s) {
    return s != null && !s.isEmpty() && s.trim().matches("-?\\d+");
}

Try / catch

try {
    boolean result = HarshadNumber.isHarshad(s);
} catch (IllegalArgumentException e) {
    if (e.getCause() instanceof NumberFormatException) {
        // parse failure; input is not a valid integer
    }
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/0a4242b6d77884a0. Report an issue: GitHub.