3

大家好,我关于堆栈溢出的第一个问题

import javax.swing.*;
import java.util.*;
import java.awt.event.*;

public class TI extends JFrame implements ActionListener
{
static int count=0;
String ct;
JTextField word;
JTextArea tohide;
public static void main(String arg[])
{
    TI ti=new TI();
}

public TI()
{

    JPanel j=new JPanel();
    JLabel def=new JLabel("Enter the text to be encrypted");
    word=new JTextField("",20);
    tohide=new JTextArea("",5,20);
    JButton jb=new JButton("COUNT");
    tohide.setBorder(BorderFactory.createLoweredBevelBorder());
    j.add(def);
    j.add(tohide);
    j.add(word);
    j.add(jb);
    add(j);
    setSize(500,500);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    jb.addActionListener(this);

}

public void actionPerformed(ActionEvent ae)
{

    String txt=tohide.getText();
    StringTokenizer stk=new StringTokenizer(txt," ");
    while(stk.hasMoreTokens())
    {
        String token=stk.nextToken();
        count++;
    }
    ct=Integer.toString(count);;
    word.setText(ct);

   }

    }

我想计算在文本区域中输入的字数。有一个逻辑错误。当我不断点击计数按钮时,字数会增加。

4

4 回答 4

7

count在重新计算字数之前,您永远不会将 重置为 0。似乎不需要count成为类变量。做出这种改变将使这种错误变得不可能。

于 2012-04-09T11:28:27.553 回答
3

使用javax.swing.text.Utilities哪个有

public static final int getWordStart(JTextComponent c, int offs)
public static final int getWordEnd(JTextComponent c, int offs)

用空格分隔是不够的。分隔符也可以是制表符、\n 等字符

于 2012-04-09T12:05:30.983 回答
1
public void actionPerformed(ActionEvent ae) {
    word.setText(String.valueOf(tohide.getText().split("\\s").length));
}
于 2012-04-09T13:11:46.667 回答
0

我正在使用以下代码来完成任务。它背后的想法是每对单词都用空格分隔。因此使用空间分割似乎很简单。如果单词包含回车,则必须在计数之前将回车替换为空字符串。我希望它有所帮助

 public int WordCount(String Words){
   //Initiate Result
     String s = Words+" "; //Add space after the received string
     String result ="";
     int i = 0;
     int count = s.length();

    try {

        for (i = 0; i <= count - 1; i++) {
              if (count - i > 1) {

                String tempString = s.substring(0, s.indexOf(" "));



                if (s.contains(" ") && (!s.isEmpty())) {
                    s = s.substring(s.indexOf(" ") + 1, s.length());
                    //get substring between " " and lenght ;
                } else {
                    if(!s.isEmpty()) {
                        //output nothing
                    } 
                }
            } else {
                //output nothing;
            }

        }


    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }




    return i;

}
于 2015-09-03T09:11:46.250 回答