需要为名为 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/