Java读取字符串输入并获取指定索引字符的方法及报错解决
报错原因分析
- 索引越界触发异常:你输入的字符串是
hii',长度为4,Java字符串索引从0开始,合法范围是0到3,但你输入了索引8,超出有效范围,直接抛出StringIndexOutOfBoundsException。 - 字符串读取不完整:原代码用
sc.next()读取字符串,这个方法会在遇到空格、制表符或换行符时停止读取,如果你输入带空格的字符串(比如hello world),只会读取hello,后续逻辑会基于不完整的字符串执行,容易引发问题。 - 缺少输入校验:代码没有对用户输入的索引做合法性检查,不管输入的索引是否在有效范围内都直接调用
charAt(),只要索引不合法就会报错。
修正方案
修正后的代码解决了上述问题,能读取完整字符串并做索引合法性校验:
import java.util.Scanner; public class string_methods { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter string : "); // 读取整行输入,包含空格 String str = sc.nextLine(); System.out.print("Enter index : "); int i = sc.nextInt(); // 校验索引是否在合法范围 if (i >= 0 && i < str.length()) { System.out.println("Char at " + i + " is " + str.charAt(i)); } else { System.out.println("Invalid index! Valid range is 0 to " + (str.length() - 1)); } sc.close(); } }
补充说明
sc.nextLine()可以读取用户输入的整行内容,包含空格,避免字符串被截断。- 索引校验逻辑确保只有当输入的索引在有效范围内时,才执行字符获取操作,否则提示合法范围,避免异常触发。
内容的提问来源于stack exchange,提问作者Varun Tripathti
相关产品推荐
相关产品推荐

