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

我正在尝试编写一个程序,当用户输入一个单词时,然后输入一个索引,这会导致程序在给定的索引处显示字符,或者给出错误告诉用户给定的索引太大。每当我运行代码并放置一个太大的索引时,我都会收到来自 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();

    }

}

错误消息:线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:3 at java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt (来源不明)在scratch.main(scratch.java:15)


拉莫斯之舞
浏览 177回答 3
3回答

天涯尽头无女友

您应该charAt在检查后致电:if (index < length ) {&nbsp; &nbsp; char inputIndex = word.charAt(index); // move this line here&nbsp; &nbsp; System.out.printf("In word \"%s\", the letter at index"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + " \"%2d\" is \'%c\'.\n"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ,word, index, inputIndex );} else {&nbsp; &nbsp; System.out.printf("too big");&nbsp; &nbsp;}该异常是由于试图在过大的索引处获取字符而引起的。所以你应该在确保索引不是太大之后尝试获取字符,对吗?

梦里花落0921

这是 try-catch 块的完美使用。尝试访问索引,如果出现错误并从那里打印,则捕获产生的异常:char inputIndex;try {&nbsp; &nbsp; inputIndex = word.charAt(index);} catch(IndexOutOfBoundsException e) {&nbsp; &nbsp; System.out.println("Out of bounds!");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python