我正在编写一个程序,该程序从文本文件获取名称并打印名称的缩写。
名称以“ Last,First M”开头。格式,每个名称都在单独的行上。
因为文本文件包含班上每个人的名字,所以本文中不包括它。
我收到的错误是: 线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:1 在java.lang.String.substring(String.java:1963) 在AS01a.main(AS01a.java:28)
/* My Name
** February 6, 2019
** Class Name
** Assignment Name
** Collaborations: None
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class AS01a{
public static void main(String args[]) throws FileNotFoundException{
String DEFAULT_FILE_NAME = "AS01.txt";
String fileName;
if (args.length != 0)
{ fileName = args[0]; }
else
{ fileName = DEFAULT_FILE_NAME; }
Scanner input = new Scanner(new File(fileName));
String fullName, first, middle, last, initials;
while(input.hasNextLine()){
fullName = input.nextLine();
//Dividing the full name into individual initials
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
middle = fullName.substring(fullName.lastIndexOf(" ")+1, fullName.lastIndexOf(" ")+2);
last = fullName.substring(0,1);
//Testing to see if the full name contains a middle name
if(fullName.indexOf(" ") == fullName.lastIndexOf(" ")){
initials = first + ". " + last + ".";
}
else{
initials = first + ". " + middle + ". " + last + ".";
}
if(input.hasNextLine()){
System.out.println(fullName + " yields " + initials);
}
}
}
}
我的结果出乎意料,唯一的问题是前面提到的错误。
答案 0 :(得分:1)
您的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);
}
}
答案 1 :(得分:1)
fullName
似乎是一个空字符串,您可以使用调试器轻松地检查它。而且它为空的原因是您的文件中可能有一个空白行。如果是这样,则应添加if (fullName.isEmpty()) continue;
之类的空支票以遍历其余行。