java - Java中的异常 "String must not end with a space"

标签 java

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

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

int wordCount(String s){
       if (s==null) throw new NullPointerException ("string must not be null");
      int counter=0;
        for(int i=0; i<=s.length()-1; i++){    
          if(Character.isLetter(s.charAt(i))){
             counter++;
             for(;i<=s.length()-1;i++){
                     if(s.charAt(i)==' '){
                             counter++;
                     }
             }
          }
     }
     return counter;
    } 

最佳答案

您的异常处理处于正确的轨道上,但还没有完全到位(正如您所注意到的)。

尝试下面的代码:

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;
}

正则表达式(或“正则表达式”)是字符串验证和搜索的绝佳工具。上面的方法采用了快速失败实现,即该方法在执行昂贵的处理任务之前会失败,而这些任务无论如何都会失败。

我建议温习一下这里介绍的两种实践:机器人正则表达式和异常处理。下面列出了一些可帮助您入门的优秀资源:

关于java - Java中的异常 "String must not end with a space",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19719218/

相关文章:

java - 1 到 100 之间的偶数(含 1 和 100)

java - 未创建日志文件

java - SimpleDateFormat 在 java 中返回一个奇怪的值

Java 程序读取用户输入直到输入 0,同时还会进行一些计算(偶数/奇数、平均值等)

java - 使用 java 程序发送的 Outlook 电子邮件中未应用粗体样式

java - FOR 循环中的 boolean 值

java - androrm 库出现 NoClassDefFoundError

java - 学习 Java 字节码和 JVM

java - 有意传递文件,我该如何检索它

java - 递增可序列化对象定义的版本 ID 的正当理由是什么?