2014-11-18 6 views
0

그래서 사용자가 입력 한 문자열의 중간 이름을 찾아서 인쇄하는 프로그램을 만들었습니다. 나는 4 개의 이름이있는 경우에도 프로그램이 중간 이름을 인쇄 할 수 있기를 원한다. "joseph alan bloggs"를 입력하면 "alan"이 인쇄되지만 "joseph alan steven bloggs"를 입력하면 "alan steven"이 인쇄됩니다.문자열의 가운데 단어에있는 단어 카운터

그래서 여기에 붙어 있습니다. 사용자가 2 개의 이름을 입력하면 또는 더 적은 수의 이름을 입력하라는 오류 메시지가 출력되지만 현재는 다음과 같은 오류가 발생합니다. 사전들에서

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; 
    } 

감사합니다 ... 다음과 같이

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) 

내 코드는

답변

0

사용자가 하나의 이름을 입력하고 첫 번째와 마지막 인덱스가 똑같아 돈이되면 귀하의 오류가 온다

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"); 
       } 

      } 
     } 
    } 
'는 t는 count.Try이 코드 루프를 필요가 있다고 생각