回文方法和比较

时间:2013-10-28 06:46:04

标签: java methods comparison palindrome

在我的程序中 - 我有2个类,PalindromeTester应该引用Palindrome中的方法findPalindrome。然而,正在发生的事情是传递给findPalindrome方法的值总是返回一个输入的字符串不是回文,即使我测试字符串,如级别或妈妈或爸爸或女士。

有人会建议改善吗?我很确定我认为我的findPalindrome方法没有正确检查字符串。我认为它的方法,但如果有人看到任何其他东西随意建议。它采用倒数第二个字符并尝试重建它,然后将其与原始字符串进行比较。

import java.util.Scanner;//import scanner class

public class PalindromeTester//class
{
   public static void main(String args[])//main method
   {
      Scanner in = new Scanner(System.in); //scanner object
      String palindrome = new String(); //string to accept user input

      String end = new String("q"); //string to determine user quitting

      for (int a = 0; a >= 0; a++){ //enter loop 
      System.out.println(); 
      System.out.println("Enter a string to check if it is a palindrome"); //ask for initial string 
      System.out.println(); 
      System.out.println("Continue entering strings until you are done. When you are done, enter q to quit."); //remind user to enter q to quit
      palindrome = in.nextLine();//take in string input
      Palindrome original = new Palindrome(palindrome); //palindrome object and passed palindrome to the constructor...but no value yet...so? 
      original = original.findPalindrome(); //call findPalindrome to determine if palindrome is a palindrome

      if (palindrome.equalsIgnoreCase(end)) //if palindrome is q and since end is q and if they are equal, a=-2.  
        a = -2; //when incrementing the max value if ++ will be -1. since -1 is not >= to 0 then for loop exits. 
      System.out.println("Thanks for trying this program"); 

     }  
   }
 }

_____________________________________________________________

    public class Palindrome { 
      String myPalindrome;  
      String myReverse; 

      public Palindrome(){
        myPalindrome = new String(""); 
        myReverse = new String(""); 
      }

      public Palindrome(String palindrome){
        myPalindrome = palindrome; 
      }

      public String findPalindrome (){

          int length = myPalindrome.length();

          for ( int i = length - 1 ; i >= 0 ; i-- )
             myReverse = myReverse + myPalindrome.charAt(i);

          if (myPalindrome.equals(myReverse))
            System.out.println("Entered string is a palindrome.");
          else
            System.out.println("Entered string is not a palindrome.");

          return (""); 
      }


    }

1 个答案:

答案 0 :(得分:1)

调用字符串构造函数时,您的代码无法初始化myReverse。因此它被初始化为null,然后附加了回文字符串。你需要解决它。 说过上面的代码甚至无法编译并且有许多基本问题。