【发布时间】:2015-02-12 16:41:35
【问题描述】:
我正在尝试使用 Stacks 编写回文类来确定用户输入的单词是否是回文。我的回文课似乎有问题。有人可以帮我识别吗?我的程序有效,但无论我输入什么单词,它都会返回该单词不是回文。
import java.util.Stack;
public class Palindrome
{
public Palindrome()
{
Stack stack = new Stack();
String input = "";
boolean isPalindrome = false;
for(int i = 0; i < input.length(); i++)
{
stack.push(i);
}
String opposite = " ";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
if(input.equals(opposite))
isPalindrome = true;
else
isPalindrome = false;
}//end main
}//end class Palindrome
这是我的 PalindromeCheck 课程:
import java.util.Scanner;
public class PalinDromeCheck
{
public static void main(String[] args)
{
Palindrome pal = new Palindrome();
Scanner type = new Scanner(System.in); //create scanner for user to type a word
String word = null; //initial word to check
String stop = null; //stops processing of word
do
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(pal.equals(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
System.out.println("Would you like to try another word? Type Y for 'Yes' or N for 'No'");
stop = type.nextLine(); //stops processing
}
while(stop.equalsIgnoreCase("y")); //continues to process and ignores upper or lowercase Y
}
}
【问题讨论】:
-
pal.equals(word)比较两个给定对象。没有办法,你会得到正确的答案。请学习尝试学习使用class、constructor、methods的基础知识,然后实现逻辑。你的回文检查码放错地方了。 -
首先你检查回文的逻辑不应该在构造函数中,而是你可以创建一个静态方法来检查回文。就像@PrerakSola 所说的相等比较两个对象,并且由于您没有覆盖 equals 方法,它正在调用 Object 类的 equals 来检查实例是否是相同的引用。
标签: java stack palindrome