【发布时间】:2016-01-15 02:36:23
【问题描述】:
我有这段代码可以在下面找到一个回文;我需要能够从用户输入字符串中删除所有数字、空格和标点符号,所以我一直在使用replaceAll。当我的代码中只有String input = str.toLowerCase(); 和String newInput = input.replaceAll("[0-9]+", ""); 时,没有问题。它删除数字并继续。但是,当我尝试添加标点符号或空格时,我得到了 StringIndexOutOfBoundsException。
示例:我输入 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是个好主意吗? -
How is there an error at index of 6 when it no longer exists?这样不是回答你的问题吗?您需要包含堆栈跟踪的相关部分,以便人们有更好的机会帮助您。
标签: java string indexing replaceall