计算句子的单词数?
count words of sentences?
我想计算我编写代码的每个句子的单词数,但是计算句子中每个单词的字符数这是我的代码
public static void main(String [] args){
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String []count_words= sentences.split(" ");
for(String count : count_words){
System.out.println("number of word is "+count.length());}
}
方法调用 count.length()
返回每个单词的长度,因为循环将每个单词分配给变量 count
。 (这个变量名很混乱。)
想要句子的字数,需要count_words
数组的大小,即count_words.length
.
String[] count_words= sentences.split(" ");
将输入参数拆分为 " "
,这意味着该数组的长度是单词数。简单地打印出长度。
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String[] count_words= sentences.split(" ");
System.out.println("number of word is "+ count_words.length);
}
示例:
oliverkoo@olivers-MacBook-Pro ~/Desktop/untitled folder $ java Main
Please type some words, then press enter:
my name is oliver
number of word is 4
我想计算我编写代码的每个句子的单词数,但是计算句子中每个单词的字符数这是我的代码
public static void main(String [] args){
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String []count_words= sentences.split(" ");
for(String count : count_words){
System.out.println("number of word is "+count.length());}
}
方法调用 count.length()
返回每个单词的长度,因为循环将每个单词分配给变量 count
。 (这个变量名很混乱。)
想要句子的字数,需要count_words
数组的大小,即count_words.length
.
String[] count_words= sentences.split(" ");
将输入参数拆分为 " "
,这意味着该数组的长度是单词数。简单地打印出长度。
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String[] count_words= sentences.split(" ");
System.out.println("number of word is "+ count_words.length);
}
示例:
oliverkoo@olivers-MacBook-Pro ~/Desktop/untitled folder $ java Main
Please type some words, then press enter:
my name is oliver
number of word is 4