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

Kem*_*mpa 1 java string-length charat

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

码:

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


}
Run Code Online (Sandbox Code Playgroud)

例外:

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

我找不到错误,也不了解异常信息。

Car*_*ate 5

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

你要

int last = text.length() - 1; // Adjust the index
char lastChar = text.charAt(last);
Run Code Online (Sandbox Code Playgroud)

  • @Kempa,请保持警惕,并将此答案标记为正确。 (2认同)