String fullWord;
String firstWord;
String secondWord;
String thirdWord;
String fourthWord;
int firstPositionOfAsterisk;
int secondPositionOfAsterisk;
int thirdPositionOfAsterisk;
int fullWordCharacters;
int firstWordCharacters;
int secondWordCharacters;
int thirdWordCharacters;
int fourthWordCharacters;
char lastLetterFirstWord;
// I will prompt the user to enter four words seperated by a *
fullWord = JOptionPane.showInputDialog("Please enter four words: ");
// I will use the position of the * to make things easier
firstPositionOfAsterisk = fullWord.indexOf("*");
firstWord = fullWord.substring(0, firstPositionOfAsterisk);
secondPositionOfAsterisk = firstWord.indexOf("*");
secondWord = fullWord.substring(firstPositionOfAsterisk + 1, secondPositionOfAsterisk);
thirdPositionOfAsterisk = secondWord.indexOf("*");
thirdWord = fullWord.substring(secondPositionOfAsterisk + 1, thirdPositionOfAsterisk);
fourthWord = fullWord.substring(thirdPositionOfAsterisk + 1);
firstWordCharacters = firstWord.length();
System.out.println(firstWord +" has a length of " + firstWordCharacters + " characters" );
secondWordCharacters = secondWord.length();
System.out.println(secondWord +" has length of " + secondWordCharacters + " characters" );
thirdWordCharacters = thirdWord.length();
System.out.println(thirdWord +" has length of " + thirdWordCharacters + " characters" );
fourthWordCharacters = fourthWord.length();
System.out.println(fourthWord +" has length of " + fourthWordCharacters + " characters" );
lastLetterFirstWord = firstWord.charAt(firstPositionOfAsterisk - 1);
System.out.println("The last letter of " + firstWord + "is " + lastLetterFirstWord);
fullWord = firstWord + secondWord + thirdWord + fourthWord;
fullWordCharacters = fullWord.length();
System.out.println(firstWord +", " + secondWord + ", " + thirdWord + ", " + fourthWord + "has length of" + fullWordCharacters);
ユーザーに「*」で区切られた 4 つの単語を入力させようとしています。たとえば、She*will*call*back のような出力が必要です。
彼女は長さ 3 ウィルは長さ 4 コールは長さ 4 バックは長さ 4
* 記号は、3、8、および 13 の位置で見つかりました。
彼女の最後のキャラクターはsです
She、will、call、backの長さは15
しかし、この java.lang.StringIndexOutOfBoundsException エラーが発生し続けます。これを修正するにはどうすればよいですか?
この行はプログラムをクラッシュさせます
secondWord = fullWord.substring(firstPositionOfAsterisk + 1, secondPositionOfAsterisk);