我正在嘗試使GUI的代碼允許用戶在JTextField中輸入一個單詞,然後檢查它是否是迴文(即Ono是一個迴文,它來回相同)。我如何拿JTextField並將它們轉換爲字符來檢查句子是否是迴文? (?而且,我怎麼會刪除空格,標點符號等),這是我當前的代碼設置我將如何採取TextField輸入,把每個字母,並把它放入字符?
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字母去測試,我可以得到似乎進入字符並被輸出的文字
EDIT2:所以我現在的主要問題,即使我可以添加東西到堆棧,是如何來我的.replace/.tolowercase的字符串不做任何事情?我在TextField中輸入的字符串不會被替換(I.e HELLO WORLD保持爲HELLO WORLD,而不是helloworld),並且我的堆棧中始終存在空值,即使它正在從inputWord獲取字母? (即HELLO將nullOLLEH)我也試圖把它變成一個字符串
compare+=stack.pop();
不過這些都不會是它增加了字母加空每個? (nullnullO,nullOL nullOLL)爲什麼它有一個null?
編輯3:它的工作!有點乏味的方式,我不得不這樣做,因爲我必須使用堆棧來比較(用於學習目的)
你爲什麼要推串到堆棧?如果你知道你想要做什麼的要點,那就向我們解釋一下。這*似乎*是要求某人爲您編寫代碼,這是不適當的。顯示你迄今爲止所做的工作,以解決你遇到的具體問題。 –
爲什麼不簡單地[扭轉'String'](http://stackoverflow.com/a/7569370/1076463)並將其與原始的 – Robin
進行比較我無法翻轉字符串,因爲我們應該使用堆棧或隊列比較字符串在一起(因爲堆棧接受字母和單詞本身將是backwords,它應該能夠比較?) –