2014-11-18 2 views
0

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

Заранее спасибо, ребята ...

ответ

0

Ваша ошибка возникает, когда пользователь вводит одно имя и первый и последний индекс становится same.I дон Не думаю, что вам нужен цикл для подсчета. Прочтите этот код:

public static void main(String args[]) { 
     Scanner sc = new Scanner(System.in); 
     boolean flag = true; 
     while (flag) { 
      System.out.print("Enter full name (at least 2 words): "); 
      // reads from the keyboard the name entered by the user 
      String name = sc.nextLine(); 
      name = name.trim(); 
      if (!name.isEmpty()) { 
       int firstSpace = name.indexOf(" "); 
       int lastSpace = name.lastIndexOf(" "); 
       if (firstSpace != lastSpace) { 
        String middelName = name.substring(firstSpace + 1, 
          lastSpace); 
        System.out.println(middelName); 
        flag = false; 
       } else { 
        System.out.println("Please enter 3 names or more"); 
       } 

      } 
     } 
    }