我有這段代碼找到下面的迴文;我需要能夠從用戶輸入字符串中刪除所有數字,空格和標點符號,所以我一直在使用replaceAll
。當我的代碼中只有String input = str.toLowerCase();
和String newInput = input.replaceAll("[0-9]+", "");
時,沒有問題。它刪除了數字並繼續。但是,當我嘗試添加標點或空格時,出現StringIndexOutOfBoundsException。什麼導致這個StringIndexOutofBounds異常?
例:I輸入Anna.55
所有replaceAll
聲明的下一行,System.out.println(newestInput);
,將打印出anna
但到達while循環時,立即引發錯誤,並指出,問題是指數6.
從我的理解(我仍然在學習Java和我不熟悉replaceAll
)與replaceAll("\\s", "")
刪除的空間將消除由以前replaceAll
語句留下的空隙,因此就沒有指數6(甚至4)。在索引6不存在時,如何發生錯誤?
import java.util.Scanner;
public class PalindromeTester {
public static void main (String[] args) {
String str;
String another = "y";
int left;
int right;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) {
System.out.println("Enter a potential palindrome:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
String input = str.toLowerCase();
String newInput = input.replaceAll("[0-9]+", "");
String newerInput = input.replaceAll("\\W", "");
String newestInput = newerInput.replaceAll("\\s", "");
System.out.println(newestInput);
while (newestInput.charAt(left) == newestInput.charAt(right) && left < right) {
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println("That string is not a palindrome.");
else
System.out.println("That string is a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
首先''input.replaceAll(「\\ W」,「」)''不應該在這裏使用'newInput'嗎?第二:是否認爲計算'right'是一個好主意,_before_你減少你的源字符串的大小? – Tom
'如果在索引爲6時出現錯誤,它不再存在嗎?'這不是回答你的問題嗎?您需要包含堆棧跟蹤的相關部分,以便人們更好地幫助您。 – John3136