gpt4 book ai didi

java - 线程 "main"java.lang.StringIndexOutOfBoundsException : String index out of range: 7 中的异常

转载 作者:行者123 更新时间:2023-11-29 07:25:59 24 4
gpt4 key购买 nike

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

代码:

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):

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

关于java - 线程 "main"java.lang.StringIndexOutOfBoundsException : String index out of range: 7 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com