doocs/leetcode · error · IllegalArgumentException

Invalid char:

Error message

Invalid char: 

What it means

English README version of the LeetCode 488 Java encoder: the switch maps only R, G, B, W, Y, and space; anything else triggers IllegalArgumentException("Invalid char: " + ch) in the default branch. The exception exists to surface malformed board/hand strings immediately instead of producing corrupted encoded state.

Source

Thrown at solution/0400-0499/0488.Zuma Game/README_EN.md:287

        }

        long stateBits = 0;
        for (char ch : stateChars) {
            stateBits = (stateBits << 3) | Zuma.encode(ch);
        }
        return stateBits;
    }

    private static long encode(char ch) {
        return switch (ch) {
            case 'R' -> 0x1;
            case 'G' -> 0x2;
            case 'B' -> 0x3;
            case 'W' -> 0x4;
            case 'Y' -> 0x5;
            case ' ' -> 0x0;
            default  ->
                throw new IllegalArgumentException("Invalid char: " + ch);
        };
    }
}
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- problem:end -->

View on GitHub (pinned to f84f361dc4)

Solutions

  1. Strip and validate: input.chars().allMatch(c -> "RGBYW ".indexOf(c) >= 0)
  2. Use trim()/strip() on lines read from input streams
  3. Add missing cases to the switch if your variant defines extra colors
  4. Log the exact input string when the exception fires to find the bad byte

Example fix

// before
encode(boardLine); // boardLine ends with '\n' -> throws

// after
encode(boardLine.strip());
Defensive patterns

Strategy: validation

Validate before calling

String line = scanner.nextLine().strip();
if (!line.matches("[RGBYW ]*")) { System.err.println("bad input: " + line); continue; }
encode(line);

Type guard

static boolean isEncodable(String s) { return s.chars().allMatch(c -> "RGBYW ".indexOf(c) >= 0); }

Try / catch

try { encode(s); } catch (IllegalArgumentException e) { if (e.getMessage().startsWith("Invalid char:")) fixInput(); else throw e; }

Prevention

When it happens

Trigger: Passing strings containing digits, lowercase color letters, '\n', '\t', or unicode chars to encode(); consuming input from stdin without stripping the newline.

Common situations: Online-judge style runners appending a newline to the last line; users substituting different color letters for variant puzzles; refactoring from char[] to String and picking up unexpected separators.

Related errors


AI-assisted analysis of doocs/leetcode@f84f361dc4 (2026-08-27). Data as JSON: /api/errors/c6ab926c17f972fe. Report an issue: GitHub.