2011-02-16 105 views
2

我試圖讓這個程序來計算連續字符的數量 和im得到錯誤,說:「字符串索引超出範圍。任何人都可以幫我 解決這個問題嗎?字符串索引超出範圍

import javax.swing.*; 

public class Project0 { 
    public static void main(String[] args){ 

     String sentence; 
     sentence = JOptionPane.showInputDialog(null, "Enter a sentence:"); /*Asks the user to 
                      enter a sentence*/ 
     int pairs = 0; 
     for (int i = 0; i < sentence.length(); i++){  //counts the pairs of consecutive characters 
      if (sentence.charAt(i) == sentence.charAt(i+1)) pairs++; 
     } 

     JOptionPane.showMessageDialog(null, "There were " + pairs + " pairs of consecutive characters"); 
    }//main 
}// Project0 

回答

2

循環中的最後一個元素是100%保證會導致問題。也許只有在你的循環中長度爲1?

考慮代碼:

for (int i = 0; i < sentence.length(); i++){ 
    if (sentence.charAt(i) == sentence.charAt(i+1)) pairs++; 
} 

String s = "AABBCC"; 

first loop, i = 0 : compare s[0] to s[1] 
first loop, i = 1 : compare s[1] to s[2] 
first loop, i = 2 : compare s[2] to s[3] 
first loop, i = 3 : compare s[3] to s[4] 
first loop, i = 4 : compare s[4] to s[5] 
first loop, i = 5 : compare s[5] to s[6] // WOAH, you can't do that! there is no s[6]!! 
0

sentence.charAt(i+1)將在for循環

0

你需要改變你的for循環的上限不全力以赴的最後一步會以此爲i + 1 > sentence.length()因爲您查找連續字符的方式是「查看i」字符,然後查看下一個「 」。一旦你到達最後,那麼不是「下一個」,所以只要停在最後一個。

for (int i = 0; i < sentence.length()-1; i++) 
相關問題