Java 是什么导致此StringIndexOutOfBoundsException?
我正在写一个程序,它从一个文本文件中提取名字并打印名字的首字母 名称采用“Last,First M.”格式,每个名称位于单独的一行 因为这个文本文件包含了我班上每个人的名字,所以我不会在这篇文章中包含它 我收到的错误是: 线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:1 位于java.lang.String.substring(String.java:1963) 位于AS01a.main(AS01a.java:28)Java 是什么导致此StringIndexOutOfBoundsException?,java,Java,我正在写一个程序,它从一个文本文件中提取名字并打印名字的首字母 名称采用“Last,First M.”格式,每个名称位于单独的一行 因为这个文本文件包含了我班上每个人的名字,所以我不会在这篇文章中包含它 我收到的错误是: 线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:1 位于java.lang.String.substring(String.java:1963) 位于AS01a.main(AS01a.java:2
我的结果与预期一致,唯一的问题是前面提到的错误。您的StringIndexOutOfBoundsException可能是由于您收到的数据,因为我们不知道“全名”。如果某人没有名字/中间名/姓氏,您将得到异常,因为在初始化第一个中间名和最后一个中间名之前,您没有检查此项。将初始值设定项移到if语句中,看看这是否有帮助
试试这个
while(input.hasNextLine()){
fullName = input.nextLine();
if(fullName.isEmpty())
fullName = input.nextLine();
//Testing to see if the full name contains a middle name
if(fullName.indexOf(" ") == fullName.lastIndexOf(" ")){
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
last = fullName.substring(0,1);
initials = first + ". " + last + ".";
}
else{
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
middle = fullName.substring(fullName.lastIndexOf(" ")+1, fullName.lastIndexOf(" ")+2);
last = fullName.substring(0,1);
initials = first + ". " + middle + ". " + last + ".";
}
if(input.hasNextLine()){
System.out.println(fullName + " yields " + initials);
}
}
fullName
似乎是一个空字符串,您可以使用调试器轻松检查这一点。它是空的原因是你的文件中可能有一个空行。如果是这样,您应该添加空检查,如If(fullName.isEmpty())continue代码>以迭代剩余的行。其中一行的格式错误。你试过调试吗?
while(input.hasNextLine()){
fullName = input.nextLine();
if(fullName.isEmpty())
fullName = input.nextLine();
//Testing to see if the full name contains a middle name
if(fullName.indexOf(" ") == fullName.lastIndexOf(" ")){
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
last = fullName.substring(0,1);
initials = first + ". " + last + ".";
}
else{
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
middle = fullName.substring(fullName.lastIndexOf(" ")+1, fullName.lastIndexOf(" ")+2);
last = fullName.substring(0,1);
initials = first + ". " + middle + ". " + last + ".";
}
if(input.hasNextLine()){
System.out.println(fullName + " yields " + initials);
}
}