为了账号安全,请及时绑定邮箱和手机立即绑定

线程“main”中的异常 java.lang.StringIndexOutOfBounds

线程“main”中的异常 java.lang.StringIndexOutOfBounds

精慕HU 2021-11-03 11:00:21
我正在尝试打印姓氏字符,但我的代码生成了异常。代码:import java.util.Scanner;public class LastCharacter {    public static void main(String[] args) {        Scanner reader = new Scanner(System.in);        System.out.println("Type your name: ");        String name = reader.nextLine();        char nameLastChar = lastCharacter(name);        System.out.println("Last character = " + nameLastChar);    }    public static char lastCharacter(String text){        int last = text.length();        char lastChar = text.charAt(last);        return lastChar;    }}例外:线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:7我找不到我的错误,我不明白异常信息。
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

如果字符串长度为 7 个字符,则最后一个索引是 6,而不是 7。请记住,索引从 0 开始。


你要


int last = text.length() - 1; // Adjust the index

char lastChar = text.charAt(last);


查看完整回答
反对 回复 2021-11-03
  • 1 回答
  • 0 关注
  • 189 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信