Java 使用方法检查回文

Java 使用方法检查回文,java,methods,palindrome,Java,Methods,Palindrome,我必须使用一些方法来测试一个句子的回文,我已经完成了大部分测试,但它只会测试字符串中的第一个单词,不会继续测试下一个单词。我相信这和空间有关,如果有人能帮忙的话,那就太好了。此外,我还没有研究数组,所以如果不使用数组,我将不胜感激 class palindromeTesting { public static void main(String[] args) { String userInput; Strin

我必须使用一些方法来测试一个句子的回文,我已经完成了大部分测试,但它只会测试字符串中的第一个单词,不会继续测试下一个单词。我相信这和空间有关,如果有人能帮忙的话,那就太好了。此外,我还没有研究数组,所以如果不使用数组,我将不胜感激

    class palindromeTesting
    {
    public static void main(String[] args)
        {
            String userInput;
            String goodWords;
            String palindromes;

            System.out.println("Please enter a sentance to be tested for palindrome: ");
            userInput = EasyIn.getString();
            userInput += " " ; 

            goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
            palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
            System.out.println("The valid palindromes are " + palindromes);

        } //Main

//--------------------------------------------------------------------------------------------------------------------------------------------------------------        

    public static String charsCheck(String userInput)
        {
            String validWords;
            String firstWord;
            Boolean goodWord;
            int spacePos;
            char letter;

            spacePos = userInput.indexOf(" ");
            validWords = "";

            while(spacePos > 0)
                {
                    firstWord = userInput.substring(0 , spacePos);
                    goodWord = true;

                    for(int index = 0 ; index < firstWord.length()  && goodWord == true ; index++)
                        {
                            spacePos = userInput.indexOf(" ");
                            letter = Character.toUpperCase(firstWord.charAt(index));

                            if(letter < 'A' || letter > 'Z' )
                                {
                                    goodWord = false;
                                }

                        } //for

                        if(goodWord == true)
                            {
                                firstWord = firstWord + " ";
                                validWords = validWords + firstWord;
                            }

                    userInput = userInput.substring(spacePos + 1);
                    spacePos = userInput.indexOf(" ");

                } //While


            return validWords;

        } //charsCheck main

//-----------------------------------------------------------------------------------------------------------------------------------------------------------       

    public static String palinCheck(String goodWords)
        {
            String firstWord;
            String validPalins = "";
            String backward = "";
            int spacePos;

            spacePos = goodWords.indexOf(" ");

            while(spacePos > 0)
                {
                    firstWord = goodWords.substring(0 , spacePos);
                    for(int i = firstWord.length()-1; i >= 0; i--) 
                        {
                            backward = backward + firstWord.charAt(i);
                        }

                    if(firstWord.equals(backward))
                        {
                            validPalins = validPalins + firstWord;
                        }

                    goodWords = goodWords.substring(spacePos + 1) ;
                    spacePos = goodWords.indexOf(" ") ; 

                }//While

            return validPalins; 

        } //palinCheck main 

//--------------------------------------------------------------------------------------------------------------------------------------------------------------

} //Class

如果您认为问题是空格,则始终可以使用replaceAll方法删除所有空格和任何其他不需要的字符。假设您有要比较的word1和word2,看看它们是否是回文,然后执行以下操作:

String word1 = "du mb";
String word2 = "b,mu d";

word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
一旦去掉了不必要的字符或空格,就应该进行检查。此外,对于此类任务,您可以始终使用正则表达式,但对于初学者来说,这可能有点难学

另外,我建议使用for循环可能可以在one for循环中完成,但是嵌套循环可以代替while循环来完成此任务。看看这个

旁注:

另外,我还没有研究数组,所以如果数组不是 用过


字符串本质上是字符数组

你所描述的问题实际上并不是正在发生的事情;您的代码确实会转到下一个单词。对于我的测试,我使用了测试输入Hi,我的名字是blolb

问题在于你的palinCheck方法。您正在使用向后变量反转单词,并检查它与第一个单词是否相等。但是,您并没有在循环中将向后变量重置回空白字符串。因此,您将不断地从上一个循环中添加到之前的内容中。在方法的末尾,如果我使用上面的测试字符串检查backward的内容,它实际上看起来像iHymemansiblolb

要解决此问题,只需在while循环中向后声明字符串,如下所示:

while(spacePos > 0) {
    String backward = "";
    // rest of loop
简要说明:

在palinCheck方法的运行过程中,每次迭代时都要更改goodWords参数:

goodWords = goodWords.substring(spacePos + 1) ;
虽然这在技术上是可接受的,但在方法之外没有效果,我认为这样修改方法参数是不好的做法。我会在方法的顶部创建一个新的字符串变量,可能会将其称为currentGoodWords或类似的名称,然后将行更改为:

currentGoodWords = goodWords.substring(spacePos + 1) ;

另外,我假设这是家庭作业,所以如果允许你使用它,我肯定会看看Elliot Frisch提到的方法。我承认,我以前从未知道过这个方法,所以Elliot对major+1。

我很久以前就把这段代码作为个人项目写在回文上,使用最短的代码量。它基本上剥离了每个非单词字符,把它放在小写,只有13行。希望这有助于哈哈!希望其他人也能幸运地找到这个

import java.util.Scanner;
public class Palindrome  {
   public static void main(String[]args){
      if(isReverse()){System.out.println("This is a palindrome.");}
      else{System.out.print("This is not a palindrome");}
   }
   public static boolean isReverse(){
     Scanner keyboard =  new Scanner(System.in);
      System.out.print("Please type something: "); 
      String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
      return (line.equals(new StringBuffer(line).reverse().toString()));
   }
}

如果你知道数组,你将在5秒钟内学会,如果你知道如何使用字符串,这是美化字符数组调用将使你的代码更短,更清晰。它返回一个字符串数组,其中每个元素都是输入的一个字,没有空格。此外,您可能会发现了解该方法的存在很有用。您可能希望查看该方法。