当前位置: 代码迷 >> Java相关 >> 帮帮忙
  详细解决方案

帮帮忙

热度:101   发布时间:2008-04-02 11:06:41.0
帮帮忙
编程定义一个类分别统计任一个字符串中的英文字母和数字字符出现的次数
----------------解决方案--------------------------------------------------------
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Stat extends JFrame{
    private JLabel label;
    private JTextArea text;
    private JButton button;
    private JPanel buttonPanel;
    private Container container;
    
    public Stat(){
        super("统计");
        label = new JLabel("请输入字符",SwingConstants.LEFT);
        text = new JTextArea("",30,60);
        button = new JButton("分析");
        button.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    int digitNum = 0,charNum = 0;
                    String str = text.getText();
                    for(int i=0;i<str.length();i++){
                        if(Character.isDigit(str.charAt(i))){
                            digitNum++;
                        }
                        else if(Character.isUpperCase(str.charAt(i)) || Character.isLowerCase(str.charAt(i))){
                            charNum++;
                        }
                    }
                    JOptionPane.showMessageDialog(container,"数字"+digitNum+"个\n字母"+charNum+"个","统计结果",JOptionPane.INFORMATION_MESSAGE);
                }
            }
        );
        buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(button);
        container = getContentPane();
        container.add(label,BorderLayout.NORTH);
        container.add(text);
        container.add(buttonPanel,BorderLayout.SOUTH);
        
        setVisible(true);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = getSize();
        setLocation((screenSize.width - frameSize.width)/2,(screenSize.height - frameSize.height)/2);
    }
    public static void main(String args[]){
        Stat stat = new Stat();
    }
}

[[it] 本帖最后由 freish 于 2008-4-3 07:03 编辑 [/it]]
----------------解决方案--------------------------------------------------------
  相关解决方案