簡體   English   中英

while(string.length> = 0)給出StringIndexOutOfBoundsException錯誤

[英]while(string.length >= 0) gives StringIndexOutOfBoundsException error

我有一個程序,其中我在計算字符串中的單詞數。 問題是,我需要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);
        }
    }

如果沒有更多空間可查,您無需檢查indexOf()的結果。

 pos = sentence.indexOf(' ');
 word = sentence.substring(0,pos);

當在其余字符串中找不到更多空間時,對indexOf()的調用將返回-1。

然后,隨后對substring(0,-1)調用將引發IndexOutOfBoundsException,因為0> -1。

從javadoc中獲取String.substring(int,int)

拋出: IndexOutOfBoundsException-如果beginIndex為負,或者endIndex大於此String對象的長度, 或者beginIndex大於endIndex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM