线程 "main" java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:7

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7

我正在尝试打印姓氏字符,但我的代码生成异常。

代码:

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;
    }


}

异常:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7

找不到我的错误,也不明白异常信息

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

你想要

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