[英]WordCount program doesn't count first word
嗨,我是新手,对于编程很困惑,我正在开发一个程序,该程序可以对句子字符串中的单词进行计数,但是即使它是唯一一个,它也不会计算字符串中的第一个单词。 我知道这与案例无关,因为我已经对此进行了测试。 任何帮助都感激不尽! 这是我的代码
public class WordCount {
public static boolean isWord (String w, int min) {
int letters=0;
for (int i=0; i<w.length(); i++) {
char c=w.charAt(i);
boolean l=Character.isLetter(c);
if (l=true) {
letters++;
}
else {
c=' ';
}
}
if (letters>min) {
return true;
}
else {
w=" ";
}
return false;
}
public static int countWords (String a, int minLength) {
int count=0;
for (int i=0; i<a.length(); i++) {
if (a.charAt(i)==' ') {
String b=a.substring(0, a.indexOf(' ')-1);
if (isWord(b, minLength)==true) {
count++;
}
}
}
return count;
}
public static void main (String[] args) {
System.out.print("Enter a sentence: ");
String sentence=IO.readString();
System.out.print("Enter the minimum word length: ");
int min=IO.readInt();
if (min<0) {
System.out.println("Bad input");
return;
}
if (sentence.length()<min) {
System.out.println("Bad input");
return;
}
System.out.println("The word count is "+ countWords(sentence,min));
}
}
问题在于您正在检查空格作为单词的定界符,因此您实际上是在计算空格而不是单词。 像“ foo”这样的单个单词没有空格,因此它将返回0,而“ foo bar”只有一个空格并且将返回1。要测试此尝试,请使用“ foo bar”(带有尾随空格)的输入得到正确的计数。
如果您对当前的实现感到满意,并且只想“使其正常工作”,则可以进行测试以查看调整后的输入长度是否大于零,如果是,则在循环运行之前在其末尾添加一个空格。
String sentence=IO.readString();
// make sure it is non-null
if (sentence!=null){
// trim spaces from the beginning and end first
sentence = sentence.trim();
// if there are still characters in the string....
if (sentence.length()>0){
// add a space to the end so it will be properly counted.
sentence += " ";
}
}
一种更简单的方法是在空间上使用String.split()
将String拆分为数组,然后对元素进行计数。
// your input
String sentence = "Hi there world!";
// an array containing ["Hi", "there", "world!"]
String[] words = sentence.split(" ");
// the number of elements == the number of words
int count = words.length;
System.out.println("There are " + count + " words.");
会给你:
有3个字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.