stanfordnlp/CoreNLP · error · NoSuchElementException

No sentiment value for integer:

Error message

No sentiment value for integer: 

What it means

SentimentClass.fromInt maps the integer sentiment scores 0-4 (produced by the sentiment annotator) to the SentimentClass enum (VERY_NEGATIVE..VERY_POSITIVE). Integers outside 0-4 hit the default branch and throw NoSuchElementException. This protects callers from malformed or unexpected sentiment scores.

Solutions

  1. Only pass integers in the 0-4 range produced by the Stanford sentiment annotator
  2. Validate/range-check the integer before calling fromInt
  3. Use the enum constants directly instead of converting raw integers

Example fix

// before
SentimentClass c = SentimentClass.fromInt(rawScore); // throws for rawScore=7
// after
if (rawScore >= 0 && rawScore <= 4) {
  SentimentClass c = SentimentClass.fromInt(rawScore);
}
Defensive patterns

Strategy: validation

Validate before calling

if (score < 0 || score > 4) {
  throw new IllegalArgumentException("Sentiment score must be 0-4, got " + score);
}

Type guard

boolean isSentimentInt(Integer i) { return i != null && i >= 0 && i <= 4; }

Try / catch

try {
  SentimentClass c = SentimentClass.fromInt(score);
} catch (NoSuchElementException e) {
  c = SentimentClass.NEUTRAL; // or log and skip
}

Prevention

When it happens

Trigger: Calling SentimentClass.fromInt(x) with x < 0 or x > 4, e.g. from a custom annotator, a misconfigured sentiment model, or manually parsed sentiment values.

Common situations: Feeding raw RNNCoreAnnotations scores that are not the standard 5-class Stanford sentiment values; older/moved sentiment models producing different class ids; arithmetic on sentiment integers (e.g. averaging then rounding) yielding out-of-range values.

Understand the failure class

Background: Invalid enum value errors: "Unknown type", "Invalid scope", "must be one of" — when a string is not on the library's allowed list — this error's family across 23 libraries.

Related errors


AI-assisted analysis of stanfordnlp/CoreNLP@1b7edd19c4 (2026-09-10). Data as JSON: /api/errors/36a828a681ae649e. Report an issue: GitHub.

Appendix: source

Thrown at src/edu/stanford/nlp/simple/SentimentClass.java:60

   *
   * @param sentiment The Integer representation of a sentiment.
   *
   * @return The sentiment class associated with that integer.
   */
  public static SentimentClass fromInt(int sentiment) {
    switch (sentiment) {
      case 0:
        return VERY_NEGATIVE;
      case 1:
        return NEGATIVE;
      case 2:
        return NEUTRAL;
      case 3:
        return POSITIVE;
      case 4:
        return VERY_POSITIVE;
      default:
        throw new NoSuchElementException("No sentiment value for integer: " + sentiment);
    }
  }
}

View on GitHub (pinned to 1b7edd19c4)