2017-02-07 73 views
-1

问题我正在编写一个程序,在一个句子中颠倒单词顺序。 (例如“红帽属于约翰”=>“约翰属于帽子红”)我走过了do-while循环,但我不明白为什么会有索引异常。StringIndexOutOfBoundsException:与String.substring()和String.indexOf()

感谢您的帮助,

JonBrown


例外:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -23 
    at java.lang.String.substring(Unknown Source) 
    at WordReverse.main(WordReverse.java:17) 

代码:

public class WordReverse 
    { 
     public static void main(String[] args) 
     { 
      String input = "The red had belongs to John"; 
      String reverse = ""; 
      int lastSpace = 0; 

      do 
      { 
      //Isolate Word w/ Preceding Space 
      int startIndex = lastSpace; 
      int endIndex = input.indexOf(' ', startIndex + 1); 

      //Add Word to front of String 
      reverse = input.substring(startIndex, endIndex) + reverse; 

      //Add Preceding Space for First Iteration 
      if (lastSpace == 0) reverse = " " + reverse; 

      //Reset Last Space 
      lastSpace = endIndex; 

      // Repeat Loop Until line14 .indexOf returns -1 due to lack of " ". 
      }while (lastSpace != -1); 

      System.out.println(reverse); 
     } 
    } 
+0

问题是与input.indexOf(””,则startIndex + 1);对输入字符串的最后一个字返回-1。 – ravthiru

回答

0

正如其他人已经指出,你的问题是与lastIndex是-1。此修复程序跳出这种情况发生时,循环的,而不是之前复制的字符串的结果的余:

public class WordReverse 
{ 
    public static void main(String[] args) 
    { 
     String input = "The red hat belongs to John"; 
     String reverse = ""; 
     int lastSpace = 0; 

     do 
     { 
      //Isolate Word w/ Preceding Space 
      int startIndex = lastSpace; 
      int endIndex = input.indexOf(' ', startIndex+1); 
      if (endIndex==-1) { 
       reverse = input.substring(startIndex) + reverse; 
       break; 
      } 

      //Add Word to front of String 
      reverse = input.substring(startIndex, endIndex) + reverse; 

      //Add Preceding Space for First Iteration 
      if (lastSpace == 0) reverse = " " + reverse; 

      //Reset Last Space 
      lastSpace = endIndex; 

      // Repeat Loop Until line14 .indexOf returns -1 due to lack of " ". 
     }while (true); 

     System.out.println(reverse); 
    } 
} 
0

只需使用一个分裂为方便

String input = "The red had belongs to John"; 

    String arr[] = input.split(" "); 

    for (int x = arr.length -1; x >= 0; x--) 
     System.out.println(arr[x]); 
0

这种解决方案更优雅:

public class WordReverse 
{ 
    public static void main(String[] args) 
    { 
     String input = "The red had belongs to John"; 
     String array = input.split(" "); 
     for(int i = array.length()-1; i >= 0; i++) 
      System.out.print(array[ i ] + " "); 
     System.out.println(); 
    } 
} 
+0

Wow input.split()是强大的,我很高兴我再也不用老式的方式去做了。 –

0

当你到达最后的空间(ri ght在“John”之前),endIndex值是-1。然后,您尝试拨打subString(),并使用小于startIndexendIndex,这会导致崩溃。