import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GetDigit extends JFrame{
private JTextArea input,output;
private JButton get,exit;
private JPanel buttonPanel;
private Container container;
public GetDigit(){
super("获取字符串中的数字");
container = getContentPane();
input = new JTextArea(10,40);
output = new JTextArea(5,40);
output.setEditable(false);
container.add(new JScrollPane(input),BorderLayout.NORTH);
container.add(new JScrollPane(output));
buttonPanel = new JPanel(new FlowLayout());
get = new JButton("获取");
get.addActionListener(new HandleGet());
exit = new JButton("退出");
exit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
}
);
buttonPanel.add(get);
buttonPanel.add(exit);
container.add(buttonPanel,BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
//使窗口居中
Dimension frameSize = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - frameSize.width)/2,(screenSize.height - frameSize.height)/2);
setVisible(true);
}
public static void main(String args[]){
GetDigit getDigit = new GetDigit();
}
class HandleGet implements ActionListener{
public void actionPerformed(ActionEvent event){
output.setText("");
char[] inputChars = input.getText().toCharArray();
int num = 0;
//用来获取字符串中数字的个数
StringBuffer digit = new StringBuffer("");
//将每次获取的数字串放到这里
boolean over = true;
for(int i = 0;i<inputChars.length;i++){
if(Character.isDigit(inputChars[i]) == true){
digit.append(inputChars[i]);
over = false;
}
else{
over = true;
}
if((over==true && digit.length()!=0) || (digit.length()!=0 && i == inputChars.length-1)){
num++;
output.append("第" +
num + "次出现的数字为:
" + digit + "\n");
digit = new StringBuffer("");
}
}
}
}
}
[[it] 本帖最后由 freish 于 2008-6-12 22:39 编辑 [/it]]