问题我正在编写一个程序,在一个句子中颠倒单词顺序。 (例如“红帽属于约翰”=>“约翰属于帽子红”)我走过了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);
}
}
问题是与input.indexOf(””,则startIndex + 1);对输入字符串的最后一个字返回-1。 – ravthiru