All for Joomla All for Webmasters

Word Character Counter in Java with Source Code

Word Character Counter in Java with Source Code: We can develop Word Character Counter in java with the help of string, AWT/Swing with event handling. Let’s see the code of creating Word Character Counter in java.

  1. String text=“hello makeforsure this is wcc tool”;
  2. String words[]=text.split(“\\s”);
  3. int length=words.length;//returns total number of words
  4. int clength=text.length();//returns total number of characters with space

Let’s see the swing code to count word and character.

  1. import java.awt.event.*;
  2. import javax.swing.*;
  3. public class WCC extends JFrame implements ActionListener{
  4. JTextArea ta;
  5. JButton b1,b2;
  6. WCC(){
  7.     super(“Word Character Counter – makeforsure.com”);
  8.     ta=new JTextArea();
  9.     ta.setBounds(50,50,300,200);
  10.     b1=new JButton(“Word”);
  11.     b1.setBounds(50,300,100,30);
  12.     b2=new JButton(“Character”);
  13.     b2.setBounds(180,300,100,30);
  14.     b1.addActionListener(this);
  15.     b2.addActionListener(this);
  16.     add(b1);add(b2);add(ta);
  17.     setSize(400,400);
  18.     setLayout(null);
  19.     setVisible(true);
  20. }
  21. public void actionPerformed(ActionEvent e){
  22.     String text=ta.getText();
  23.     if(e.getSource()==b1){
  24.         String words[]=text.split(“\\s”);
  25.         JOptionPane.showMessageDialog(this,“Total words: “+words.length);
  26.     }
  27.     if(e.getSource()==b2){
  28.         JOptionPane.showMessageDialog(this,“Total Characters with space: “+text.length());
  29.     }
  30. }
  31. public static void main(String[] args) {
  32.     new WCC();
  33. }
  34. }
PinIt
submit to reddit

Leave a Reply

Top