【发布时间】:2018-09-17 12:02:56
【问题描述】:
我正在尝试编写一个程序,当用户输入一个单词时,然后是一个索引,这会导致程序在给定的索引处显示字符,或者给出错误告诉用户给定的索引太大。每当我运行代码并放置一个太大的索引时,我都会从 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();
}
}
错误信息: 线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt(Unknown Source) 中的 3 ) 在scratch.main(scratch.java:15)
【问题讨论】:
-
你看过
String.fomat()吗? -
你得到什么错误信息?
-
考虑为所有读取使用相同的
Scanner实例,您不需要多个。 -
“我收到一条错误消息” - 错误消息包含许多有用的信息,可帮助您找出问题的原因。当您收到错误消息时,请在您的问题中包含完整、准确的错误消息 - 不要只说“我收到错误”。这样可以更轻松地为您提供帮助。
-
永远不要将更多信息放入 cmets,而是始终更新您的问题。