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

Java代码报错String Index out of range:1 求原因与解决办法

问题分析与解决

嘿,我一眼就揪出你代码里的问题啦!

报错原因

你这段代码抛出String Index out of range: 1的核心问题出在这行:

arr_ctext[i] = (int) arr_cipher_input[i].charAt(i);

当你用cipher_input.split("")把字符串拆分成数组后,数组里的每个元素都是单个字符的字符串(比如输入"hello"会得到["h","e","l","l","o"]),每个元素的长度只有1,合法索引只有0。但你在循环里用charAt(i),当i=1时,你试图访问arr_cipher_input[1](也就是"e")的第1个索引——这显然超出了它的范围,直接触发了索引越界异常。

解决方法

给你三种可行的修复方案,选最适合你的就行:

方案1:直接使用原字符串的charAt()(最简洁)

完全没必要拆分字符串数组,原字符串本身就支持通过索引直接获取字符,一步到位:

Scanner user_input = new Scanner(System.in);
String cipher_input = user_input.nextLine();
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
    arr_ctext[i] = (int) cipher_input.charAt(i); // 直接调用原字符串的charAt方法
}

方案2:如果非要用拆分后的数组,修改charAt的索引

既然拆分后的每个元素都是单个字符的字符串,那只需要取索引0的位置即可:

Scanner user_input = new Scanner(System.in);
String cipher_input = user_input.nextLine();
String[] arr_cipher_input = cipher_input.split("");
int[] arr_ctext = new int[cipher_input.length()];
for (int i = 0; i < cipher_input.length(); i++) {
    arr_ctext[i] = (int) arr_cipher_input[i].charAt(0); // 把i改成0
}

方案3:用toCharArray()直接获取字符数组(更高效)

Java的String类提供了toCharArray()方法,可以直接将字符串转换为char类型数组,操作起来更直观高效:

Scanner user_input = new Scanner(System.in);
String cipher_input = user_input.nextLine();
char[] charArray = cipher_input.toCharArray();
int[] arr_ctext = new int[charArray.length];
for (int i = 0; i < charArray.length; i++) {
    arr_ctext[i] = (int) charArray[i];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:17:58