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個字分隔由「*」,例如她會* * *電話回來,我想輸出喜歡這樣爲什麼在運行這個程序時會出現這個java.lang.StringIndexOutOfBoundsException錯誤?
她有長3 會具有長度爲4 呼叫具有長度4 背面具有長度4
中的*符號的位置處發現的:3,圖8和13
的最後一個字符的她爲s
她,將,呼叫,回來的長度是15
但我不斷收到此java.lang.StringIndexOutOfBoundsException錯誤。我該如何解決?
這條線崩潰程序
secondWord = fullWord.substring(firstPositionOfAsterisk + 1,secondPositionOfAsterisk);