Java 字符串索引越界异常(charAt)
我有一个示例代码:Java 字符串索引越界异常(charAt),java,Java,我有一个示例代码: while (reader.hasNext()) { String example = reader.nextLine(); if (example.charAt(0) == '.') { break; } else { if (test(example)) { System.out.println("
while (reader.hasNext()) {
String example = reader.nextLine();
if (example.charAt(0) == '.') {
break;
} else {
if (test(example)) {
System.out.println("ok");
} else {
System.out.println("no");
}
}
}
当我运行它时,我收到了一个通知
输入:
It's an example.
aabb ccdd.
.
.
输出
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
如何解决这个问题?要回答这个问题,让我问你:空字符串的第一个字符是什么
在此之前,您可能需要使用一个额外的检查
charAt
:)我假定您的读者没有阅读任何内容。示例为空字符串可能与我为readerUnrelated使用的@stinepike的Scanner
重复:不要将hasNext()
与nextLine()混用。仅在正确的对中使用它们,即hasNextLine()
/nextLine()
用于行读取,或hasNext()
/next()
用于令牌读取。这意味着我必须使用if(例如.trim().length()>0)
用于之前的检查:)对实际上,您可以只获取长度并将其与0进行比较,但是如果您的test
方法修剪字符串,则最好使用已修剪的字符串进行检查。