You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理索引不存在异常?解析数字字符串长度不足的Java代码处理方案

Handling Variable-Length Numeric Strings for Function Calls

Great question—this is a super common edge case when dealing with variable input! The core problem here is that your code assumes the parsed list will always have exactly 3 elements, but when it doesn’t, List.get() throws an unhelpful IndexOutOfBoundsException. Here are a few practical, business-aligned fixes to handle this:

Option 1: Strict Input Validation (Throw Clear Exceptions)

If your VacById method requires exactly 3 parameters to work correctly, validate the list length upfront. This avoids generic runtime errors and makes your expectations explicit:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

// Parse the input string directly from the split array (more efficient than List.of())
List<Long> longNumbers = Arrays.stream(s.split(", "))
    .map(Long::parseLong)
    .collect(Collectors.toList());

// Validate we have exactly 3 elements before proceeding
if (longNumbers.size() != 3) {
    throw new IllegalArgumentException(
        String.format("Expected 3 comma-separated numbers, but received %d", longNumbers.size())
    );
}

// Safe to retrieve elements now
long nr1 = longNumbers.get(0);
long nr2 = longNumbers.get(1);
long nr3 = longNumbers.get(2);
vaccinationService.VacById(nr1, nr2, nr3);

Option 2: Pad Missing Values with Defaults

If your service can accept default values for missing parameters (like 0 or a business-specific sentinel value), pad the list to ensure it always has 3 elements:

List<Long> longNumbers = Arrays.stream(s.split(", "))
    .map(Long::parseLong)
    .collect(Collectors.toList());

// Fill with your chosen default until we have 3 elements
while (longNumbers.size() < 3) {
    longNumbers.add(0L); // Replace with a default that makes sense for your use case
}

// Retrieve values safely
long nr1 = longNumbers.get(0);
long nr2 = longNumbers.get(1);
long nr3 = longNumbers.get(2);
vaccinationService.VacById(nr1, nr2, nr3);

Option 3: Skip the Call for Invalid Input

If calling VacById isn’t critical when input is incomplete, add a condition to only execute the call when you have exactly 3 elements, and handle the invalid case separately (like logging an error):

List<Long> longNumbers = Arrays.stream(s.split(", "))
    .map(Long::parseLong)
    .collect(Collectors.toList());

if (longNumbers.size() == 3) {
    long nr1 = longNumbers.get(0);
    long nr2 = longNumbers.get(1);
    long nr3 = longNumbers.get(2);
    vaccinationService.VacById(nr1, nr2, nr3);
} else {
    // Log the issue or notify the user as needed
    System.err.println("Skipping vaccination lookup: invalid number of parameters provided");
}

A quick optimization note: Instead of List.of(s.split(", ")) (which creates an immutable list first), using Arrays.stream() directly on the split array is more efficient and cleaner.

内容的提问来源于stack exchange,提问作者Andrew Lennox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:43:12