我正在尝试编写一个程序,当用户输入一个单词时,然后输入一个索引,这会导致程序在给定的索引处显示字符,或者给出错误告诉用户给定的索引太大。每当我运行代码并放置一个太大的索引时,我都会收到来自 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)
天涯尽头无女友
梦里花落0921
相关分类