在我下面的程序中 - 我有 2 个类,PalindromeTester 应该引用 Palindrome 中的方法 findPalindrome。但是,发生的情况是传递给 findPalindrome 方法的值总是返回一个 Entered 字符串不是回文,即使我测试了诸如 level 或 mom 或 dad 或 madam 之类的字符串。
有人可以提出改进的建议吗?我很确定我认为我的 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 ("");
}
}