我正在尝试使用允许用户在 JTextField 中输入单词然后让它检查它是否是回文的 GUI 编写代码(即 Ono 是回文,它来回相同)。我将如何获取 JTextField 并将它们转换为字符以检查句子是否为回文?(另外,我将如何删除空格、标点符号等?)这是我当前设置的代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Stack;
/**
* Write a description of class Palidromania_Kevin here.
*
* @author Kevin Hy
* @version 09/23/13
*/
public class Palindromania extends JFrame
{
public JPanel panel1,panel2;
public JLabel main1;
public JButton check;
public JTextField enterPal;
public String inputWord,letter;
public int num;
public char checker;
public Stack<String> stack = new Stack<String>();
public Palindromania ()
{
super ("Palindromania Checker");
setSize (1024,768);
Container container = getContentPane();
panel1 = new JPanel();
panel1.setBackground (new Color(10,50,50));
panel1.setLayout (new FlowLayout());
panel2 = new JPanel();
panel2.setBackground (new Color(255,255,255));
panel2.setLayout (new FlowLayout());
main1 = new JLabel ("Palindromania Checker");
check = new JButton("Verify Palindrome");
ButtonHandler handler = new ButtonHandler();
check.addActionListener(handler);
enterPal = new JTextField(8);
container.add(panel1,BorderLayout.NORTH);
container.add(panel2,BorderLayout.CENTER);
panel2.add(enterPal);
panel2.add(check);
setVisible(true);
}
public static void main (String [] args)
{
Palindromania application = new Palindromania ();
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource () == check)//Check if palindrome button
{
inputWord="";letter="";
inputWord=enterPal.getText();
inputWord=inputWord.toLowerCase();
inputWord=inputWord.replace("[ !'-,]","");
for (int x=0; x<=inputWord.length()-1;++x)//inputs lettes into the stack
{
checker=inputWord.charAt(x);
letter+=checker;
stack.add(letter);
letter="";
JOptionPane.showMessageDialog (null, stack.peek());
}
for (int x=0; x<=inputWord.length()-1;++x)//inputs lettes into the stack
{
checker=inputWord.charAt(x);
letter+=checker;
stack.add(letter);
if (letter.equals(stack.pop()))
num+=1;
letter="";
}
if (num==inputWord.length())
JOptionPane.showMessageDialog (null, "You have a palindrome!");
else
JOptionPane.showMessageDialog (null, "This is not a palindrome, sorry!");
}
}
}
} 编辑:我修改了代码,解析字符串出错,我可以让 char 字母进入测试,我可以让出现的单词进入 char 并输出
EDIT2:所以我现在的主要问题是,即使我可以将东西添加到堆栈中,我的字符串上的 .replace/.tolowercase 怎么没有做任何事情?我在 TextField 中输入的字符串不会被替换(即 HELLO WORLD 保持为 HELLO WORLD,而不是 helloworld),并且我的堆栈中总是有一个空值,即使它从 inputWord 中获取字母?(即 HELLO 将是 nullOLLEH)我还尝试将其放入字符串中
compare+=stack.pop();
但它所做的只是将带有 null 的字母添加到每个字母中吗?(nullnullO, nullOL nullOLL) 为什么它有一个空值?
EDIT3:它有效!我必须这样做的方式有点乏味,因为我必须使用堆栈进行比较(出于学习目的)