[英]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.