设有英文短文,请编写代码实现:
*1 统计以字母 w 开头的单词数;
*2 统计单词中含“or”字符串的单词数;
*3 统计长度为 3 的单词数。
*4 统计有多少单词。
Last fall I walked with a friend in hometown. He was recognized as the most stupid among my childhood playmates, but he has now been Number One in an enterprise. When we came to a fork, a blind man walked from another direction. Testing the road with his bamboo pole, the blind man was walking very slowly towards the road we were going to. I chatted with my friend as we were walking. I talked about my five job-hoppings within two years and the experiences I was still struggling in the plight now. My friend nodded and smiled, but he kept silent all along. After a while, I occasionally looked back and found the blind man had vanished.
for方法:
package com.me;
import java.util.Scanner;
public class Danci1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
@SuppressWarnings("resource") //批注允许选择性地取消特定代码段(即类或方法)中的警告
Scanner scan =new Scanner(System.in);
System.out.println("请输入文章:"); //提示用户输入
String src = scan.nextLine(); //等待用户在命令行输入一行文本回车
String[] wordList = src.split(" "); //根据空格将字符串s分割成字符串数组
int count = wordList.length; //将字符串数组分割成多少部分的值赋给count,从而得到有多少个单词
System.out.printf("总共单词量为;%d个\n",count);
int w = 0, or =0, three = 0;
for(String word : wordList) {
if(word.startsWith("w")) {
w++;
}
if(word.contains("or")) {
or++;
}
if(word.length() == 3) {
three++;
}
}
System.out.printf("w开头的单词有:%d 个\n",w);
System.out.printf("包含or的单词有:%d 个\n",or);
System.out.printf("长度为3的单词有:%d 个\n",three);
}
}
运行效果:
do...while方法:
package com.me;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Danci2 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
@SuppressWarnings("resource") //批注允许选择性地取消特定代码段(即类或方法)中的警告
Scanner sc =new Scanner(System.in);
System.out.println("请输入文章:"); //提示用户输入
String s = sc.nextLine(); //等待用户在命令行输入一行文本回车
StringTokenizer st = new StringTokenizer(s," "); //根据空格将字符串s,且显示空格
int numble = st.countTokens(); //将字符串数组分割成多少部分的值赋给numble,从而得到有多少个单词
System.out.printf("单词个数为;%d个\n",+numble);
int fircount = 0, seccount =0, thicount = 0;
int i =0;
String str[]=s.split(" "); //根据空格把字符串s分割成字符数组
do {
if(str[i].charAt(0)=='w') {
fircount++;
}
if(str[i].contains("or")) {
seccount++;
}
if(str[i].length()==3) {
thicount++;
}
i++;
}
while(i<str.length);
System.out.printf("w开头的单词有:%d 个\n",+fircount);
System.out.printf("包含or的单词有:%d 个\n",+seccount);
System.out.printf("长度为3的单词有:%d 个\n",+thicount);
}
}
运行效果: