我有一个程序,我在计算字符串中的单词数。问题是,我需要我的while循环运行一定次数。每次运行时,我都会创建一个子字符串来切断第一个单词。
程序:
public class WordCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
String sentence = "My name is Brad";
int pos;
String word;
String newSent;
int wordCount = 0;
while(sentence.length() >= 0){
pos = sentence.indexOf(' ');
word = sentence.substring(0,pos);
newSent = sentence.substring(pos+1);
sentence = newSent;
wordCount++;
System.out.println("word = " + word);
System.out.println("newSent = " + newSent);
System.out.println("wordCount = " + wordCount);
}
}
问题是永远不会计算最后一个词,因为错误发生时就是这样。
输出:
word = My
newSent = name is Brad
wordCount = 1
word = name
newSent = is Brad
wordCount = 2
word = is
newSent = Brad
wordCount = 3
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at assignment3.WordCount.main(WordCount.java:18)
更新
pos = sentence.indexOf(' ');
word = sentence.substring(0,pos);
newSent = sentence.substring(pos+1);
sentence = newSent;
if (sentence.indexOf(' ') == -1){
newSent = "";
word = sentence;
}
if (word.length() >= minLength){
wordCount++;
}
编辑2:我的解决方案是任何人都很好奇
public static void main(String[] args) {
// TODO Auto-generated method stub
String sentence = "My name is Brad";
int pos;
String word;
String newSent;
int minLength = 0;
int wordCount = 0;
// sentence.indexOf(' ') != -1
while(sentence.length() > 0){
if (sentence.indexOf(' ') == -1){
pos = sentence.length();
newSent = "";
} else {
pos = sentence.indexOf(' ');
newSent = sentence.substring(pos+1);
}
word = sentence.substring(0,pos);
sentence = newSent;
if (word.length() >= minLength){
wordCount++;
}
System.out.println("word = " + word);
System.out.println("newSent = " + newSent);
System.out.println("wordCount = " + wordCount);
}
}
答案 0 :(得分:4)
对于没有更多空格的情况,您不会检查indexOf()
的结果。
pos = sentence.indexOf(' ');
word = sentence.substring(0,pos);
当剩余字符串中没有更多空格时,对indexOf()
的调用将返回-1。
然后对substring(0,-1)
的后续调用将抛出IndexOutOfBoundsException,因为0> -1。
来自String.substring(int,int)的javadoc:
<强>抛出:强> IndexOutOfBoundsException - 如果beginIndex为负数,或者endIndex大于此String对象的长度,则或beginIndex大于endIndex 。