有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java回文被终止

主要课程(必修)

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”、“Kayak”,但带有空格和字符的回文无效


共 (1) 个答案

  1. # 1 楼答案

    你按错误的顺序做:

        // 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");