主类(必填)
import java.util.*;
public class FindingPalindrome {
private String inputString;
private Stack<Character> stack = new Stack<Character>();
public FindingPalindrome(String str)
{
inputString = str;
fillStack();
}
public void fillStack()
{
for(int i = 0; i < inputString.length(); i++)
{
stack.push(inputString.charAt(i));
}
}
public String reverseString()
{
String result = new String();
while(!stack.isEmpty())
{
result = result.concat(Character.toString(stack.pop()));
}
return result;
}
public boolean isPalindrome()
{
if(inputString.equalsIgnoreCase(reverseString()))
return true;
else return false;
}
}
测试员类(必填)
import java.util.*;
public class TestPalindrome
{
private static Scanner s;
public static void main(String args[])
{
s = new Scanner(System.in);
System.out.println("Enter the string");
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]","");
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
}
}
每当我添加“Stop!pots”时,代码就会终止并且不会打印输出。我还添加了replaceAll()
,但它也没有用。简单的回文工作“ada”,“皮划艇”,但有空格和字符的回文不起作用
答案 0 :(得分:0)
你这样做的顺序错误:
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<<<<< too late.
// You created sb with the original
// including punctuation
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
替换为
// Read the data
String st1=s.nextLine();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<< moved this
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1); // <<<< now this is a copy without punctuation
// Reverse the letters
sb.reverse();
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");