Java 例外情况;字符串不能以空格结尾;在爪哇

Java 例外情况;字符串不能以空格结尾;在爪哇,java,Java,需要为一个名为wordCount()的方法编写一个方法签名,该方法接受一个字符串参数,并返回该字符串中的字数。 就本问题而言,“单词”是任何字符序列;它不一定是一个真正的英语单词。单词之间用空格隔开。 例如:wordCount(“Java”)应返回值1 我已经写了一段代码,但问题在于抛出异常。我的错误是:“包含的字符串在java中不得以空格结尾”和“包含的字符串在java中不得以空格开头” 我的尝试: int字数(字符串s){ 如果(s==null)抛出新的NullPointerExceptio

需要为一个名为wordCount()的方法编写一个方法签名,该方法接受一个字符串参数,并返回该字符串中的字数。 就本问题而言,“单词”是任何字符序列;它不一定是一个真正的英语单词。单词之间用空格隔开。 例如:wordCount(“Java”)应返回值1

我已经写了一段代码,但问题在于抛出异常。我的错误是:“包含的字符串在java中不得以空格结尾”和“包含的字符串在java中不得以空格开头” 我的尝试:

int字数(字符串s){
如果(s==null)抛出新的NullPointerException(“字符串不能为null”);
int计数器=0;

对于(int i=0;i我将使用
String.split()
方法。这需要一个正则表达式,它返回一个包含子字符串的字符串数组。从那里很容易获得并返回数组的长度

这听起来像是家庭作业,所以我将把特定的正则表达式留给您:但它应该非常短,甚至可能只有一个字符长。

我会使用。它会更准确,因为standart String.split()即使在这种简单的情况下也不能正常工作:

// there is only two words, but between 'a' and 'b' are two spaces
System.out.println("a  b".split(" ").length);// print '3' becouse but it think than there is 
// empty line between these two spaces
使用番石榴,您可以做到以下几点:

Iterables.size(Splitter.on(" ").trimResults().omitEmptyStrings().split("same  two_spaces"));// 2

我会使用
String.split()
来处理这种情况。它将比粘贴的代码更有效。请确保检查是否有空字符。这将有助于处理多空格的句子(例如,“this_consuments_有两个空格)

public int字数(最后一个字符串句子){
int字数=0;
String trimmed句子=句子.trim();
String[]words=trimmedstatement.split(“”);
for(int i=0;i
您处理异常的方法是正确的,但还不完全正确(正如您所注意到的)

请尝试以下代码:

public int wordCount(final String sentence) {
    // If sentence is null, throw IllegalArgumentException.
    if(sentence == null) {
        throw new IllegalArgumentException("Sentence cannot be null.");
    }
    // If sentence is empty, throw IllegalArgumentException.
    if(sentence.equals("")) {
        throw new IllegalArgumentException("Sentence cannot be empty.");
    }
    // If sentence ends with a space, throw IllegalArgumentException. "$" matches the end of a String in regex.
    if(sentence.matches(".* $")) {
        throw new IllegalArgumentException("Sentence cannot end with a space.");
    }
    // If sentence starts with a space, throw IllegalArgumentException. "^" matches the start of a String in regex.
    if(sentence.matches("^ .*")) {
        throw new IllegalArgumentException("Sentence cannot start with a space.");
    }

    int wordCount = 0;

    // Do wordcount operation...

    return wordCount;
}
正则表达式(或“regex”对于那些有知识的酷孩子来说)是字符串验证和搜索的绝佳工具。上面的方法实践了快速实现失败,也就是说,该方法在执行昂贵的处理任务之前会失败,而这些任务无论如何都会失败

我建议您温习一下这里介绍的两种实践,bot regex和异常处理。下面是一些帮助您入门的优秀资源:


i@JohnGaughan-重点是异常没有发生,但需要发生。@Hot-Licks-啊,我现在明白了,重新阅读问题要慢一些。起初听起来他好像在得到这些异常,但它们不同于我所看到的任何内置异常,所以我应该知道。我只使用charAt(0)而不是
匹配和charAt(句子.长度()-1),与blank相比。@HotLicks是的,这也有效。我通常使用regex进行验证,因为它简洁、整洁且易于阅读(前提是您熟悉regex)。我熟悉regex,但我总是要搔搔头几分钟(可能还要参考参考资料)找出一个答案。
charAt
要简单得多。但这两种方法都比用
split
来捣乱要好得多(我认为这是可行的,但难度很小)。
 public int wordCount(final String sentence) {
    int wordCount = 0;
    String trimmedSentence = sentence.trim();
    String[] words = trimmedSentence.split(" ");
    for (int i = 0; i < words.length; i++) {
        if (words[i] != null && !words[i].equals("")) {
            wordCount++;
        }
    }
    return wordCount;
}
public int wordCount(final String sentence) {
    // If sentence is null, throw IllegalArgumentException.
    if(sentence == null) {
        throw new IllegalArgumentException("Sentence cannot be null.");
    }
    // If sentence is empty, throw IllegalArgumentException.
    if(sentence.equals("")) {
        throw new IllegalArgumentException("Sentence cannot be empty.");
    }
    // If sentence ends with a space, throw IllegalArgumentException. "$" matches the end of a String in regex.
    if(sentence.matches(".* $")) {
        throw new IllegalArgumentException("Sentence cannot end with a space.");
    }
    // If sentence starts with a space, throw IllegalArgumentException. "^" matches the start of a String in regex.
    if(sentence.matches("^ .*")) {
        throw new IllegalArgumentException("Sentence cannot start with a space.");
    }

    int wordCount = 0;

    // Do wordcount operation...

    return wordCount;
}