我試圖讓這個程序來計算連續字符的數量 和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