如何打印错误消息,指出用户输入索引太大?

0 java string

我正在尝试编写一个程序,当用户输入一个单词,然后是一个索引,这会导致程序显示给定索引处的字符,或者给出错误,告诉用户给出的索引太大.每当我运行代码并放置一个太大的索引时,我会从java中收到一条错误消息.任何帮助表示赞赏!

import java.util.Scanner;
public class scratch {
    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);
        System.out.printf("Enter a word:");
        String word = reader.next();

        Scanner letter = new Scanner (System.in);
        System.out.printf("Enter an index:");
        int index = letter.nextInt();

        char inputIndex = word.charAt(index);
        int length = word.length();
        if (index < length - 1 ) {
            System.out.printf("In word \"%s\", the letter at index"
                + " \"%2d\" is \'%c\'.\n"
                ,word, index, inputIndex );

        } else {
            System.out.printf("too big");   
        }
        reader.close();
        letter.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

错误消息:线程"main"中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:java.base上的java.base/java.lang.StringLatin1.charAt(未知源)中的3(java.base/java.lang.String.charAt (未知来源)at scratch.main(scratch.java:15)

Swe*_*per 6

你应该charAt在检查后打电话:

if (index < length ) {
    char inputIndex = word.charAt(index); // move this line here
    System.out.printf("In word \"%s\", the letter at index"
            + " \"%2d\" is \'%c\'.\n"
            ,word, index, inputIndex );

} else {
    System.out.printf("too big");   
}
Run Code Online (Sandbox Code Playgroud)

尝试在索引太大的情况下获取字符会导致异常.所以你应该在确保索引不是太大之后尝试获取角色,对吧?