【发布时间】:2014-11-18 20:01:27
【问题描述】:
所以我编写了一个程序,该程序本质上是查找并打印用户输入的字符串的中间名。我希望程序能够打印中间名,即使有 4 个名字,例如;输入“joseph alan bloggs”会输出“alan”,但输入“joseph alan steven bloggs”也会输出“alan steven”
所以这是我坚持的一点,我想要它,这样如果用户输入 2 个或更少的名称,则会打印一条错误消息,告诉用户输入更多名称,但目前我收到以下错误。
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1937)
at W4T2C.main(W4T2C.java:39)
我的代码如下
Scanner sc = new Scanner(System.in);
int count = 0;
while (count < 2)
{
System.out.print("Enter full name (at least 2 words): ");
String name = sc.nextLine();
// reads from the keyboard the name entered by the user
String[] numNames = name.split(" ");
// splits the string into different arrays by where the spaces are i.e. into the names
for (int i = 0; i < numNames.length; i++)
{
if (numNames[i].equals(" "))
{
}
else
{
count++;
System.out.println("Please enter 3 names or more");
// counts the number of names entered
int firstSpace = name.indexOf(" ");
// finds the index of the first space in the name
int lastSpace = name.lastIndexOf(" ");
// finds the index of the last space in the name
String middleName = "";
// initially sets the middle name as nothing
middleName = name.substring(firstSpace + 1, lastSpace);
// sets the middle name as the set of string in between the index of the
// first space plus 1 and the last space i.e. the middle name/names
System.out.println(middleName);
// prints the middle name
break;
}
提前谢谢各位...
【问题讨论】: