当 JTextArea 为空时,我的代码计算了错误的字数

My code counts the wrong number of words when the JTextArea is empty

我想在单击按钮时计算某个 JTextArea 中的单词数,但是当我 运行 我的代码在文本区域为空时我得到的单词数是 1。我不知道我的代码有什么问题。这是我的代码。

private void convertButton1MouseClicked(java.awt.event.MouseEvent evt) {                                            
    String text = inputField.getText();
    int wordCount = text.split("\s").length;
    numberOfWords.setText(String.valueOf(wordCount));

对正则表达式一无所知,但似乎这是拆分方法的默认行为。

似乎总是 return 具有原始值的数组,即使该值恰好是空字符串。

我尝试了一些简单的方法,例如:

public static void main(String[] args) throws Exception
{
    int wordCount = "".split("a").length;
    System.out.println( wordCount );
}

而且无论我尝试在哪个字符上拆分,它总是显示“1”。

解决方案可能是这样的:

    String text = inputField.getText();
    int wordCount = text.isEmpty() ? 0 : text.split("\s").length;
    numberOfWords.setText(String.valueOf(wordCount));