Итак, я создал программу, которая по существу находит и печатает средние имена строки, введенной пользователем. Я хочу, чтобы программа могла печатать средние имена, даже если есть 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;
}
Заранее спасибо, ребята ...