Now I want to count the words in the text. But the problem is that one is displayed on any text. I can type 30 words, but it will display one. Here is the code

import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.util.Scanner; /** * Created by ТыжАдмин on 01.11.2016. */ public class Wind extends JFrame { public Wind() { Font font = new Font("Comic Sans MS", Font.BOLD, 12); Font font2 = new Font("ALGERIAN", Font.BOLD, 20); Font font3 = new Font("Berlin Sans FB", Font.BOLD, 15); Font font4 = new Font("Berlin Sans FB", Font.BOLD, 18); Font font5 = new Font("Tahoma", Font.BOLD, 12); setTitle(" AI UK "); setBackground(Color.orange); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setBounds(999, 700, 1600, 950); setLayout(null); JButton x = new JButton("Обработать текст "); x.setBounds(512, 89, 190, 55); x.setFont(font); x.setBackground(Color.CYAN); add(x); JLabel nfw = new JLabel("The number of words : "); nfw.setFont(font3); nfw.setBounds(800, 110, 290, 150); add(nfw); JTextField textField = new JTextField(); textField.setBounds(900, 193, 60, 50); add(textField); JTextArea txt = new JTextArea(); txt.setBounds(32, 167, 700, 550); txt.setLineWrap(true); txt.setWrapStyleWord(true); txt.setFont(font2); add(txt); JLabel grk = new JLabel("Tne number of grammar constructions : "); grk.setFont(font4); grk.setBounds(800,201,355,180); add(grk); JLabel ps = new JLabel("Present Simple constructions : "); ps.setFont(font3); ps.setBounds(800,270,290,150); add(ps); JTextField psi = new JTextField(); psi.setBounds(900,359,60,50); add(psi); JLabel pp = new JLabel("Present Perfect constructions : "); pp.setFont(font3); pp.setBounds(800,380,290,150); add(pp); JTextField ppe = new JTextField(); ppe.setBounds(900,463,60,50); add(ppe); String s = txt.getText(); String [] TAR = s.split(String.valueOf(new char[]{' '})); int tl; tl = TAR.length; x.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { textField.setText(String.valueOf(tl)); } }); 

How can all words be displayed normally? Are there any errors in my method?

  • To format the code, use the four space indents or the {} button. - AivanF.
  • when the button is actionPerformed , the code is executed inside the actionPerformed , respectively. it should not only display the contents of tl but also calculate its value (starting with txt.getText() ) - zRrr

2 answers 2

If the word delimiter is a space, use the following:

 String [] TAR = s.split(" "); 

Few people want to understand the code where the variable names sound like: x, pp, pl, ps, etc. It will not be superfluous to read the book "Code convention", it is not big.

    Number of words can be derived as follows:

     jtextField.setText(txt.getText().split(" ").length); 

    I like to write nested commands :-)