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, and back的长度是15
但我不断收到这个 java.lang.StringIndexOutOfBoundsException 错误。我该如何解决?
此行使程序崩溃
secondWord = fullWord.substring(firstPositionOfAsterisk + 1, secondPositionOfAsterisk);