问题
I need to figure out how to make a program that counts the words in a sentence that the user inputs. The user also inputs the length that each word must be. So, if the user inputs 5 letter words, and the sentence includes a 4 letter word; that word won't be counted.
This is all I have...
public class wordcount {
public static void main(String[] args) {
int length = IO.readInt();
String sentence = IO.readString();
int full = sentence.length();
int wordcount = 0;
for(int i = 0; i < length; i++){
}
System.out.print(wordcount);
}
}
回答1:
return sentence.split("\\s+").length;
回答2:
This will read counts for an input line.
public static void main(String[] args) {
Scanner scanner = new Scanner( System.in );
int length = scanner.nextInt();
String sentence = scanner.nextLine();
scanner.close();
int wordcount = 0;
String[] words = sentence.split(" ");
for(int i = 0; i < words.length; i++){
if(words[i].length() >= length ){
wordcount++;
}
}
System.out.print(wordcount);
}
}
来源:https://stackoverflow.com/questions/12945357/i-need-a-program-for-a-wordcount