请教各位大神一个用运用IO流统计英文单词的问题

jjzzggkk 2016-05-15 01:53:21
编写程序ListWords.java实现从键盘输入一个英文句子,统计该句子中英文单词的个数,
将找出所有单词存放到一个数组中。例如:He said,"Ths's not a good idea."则输出

共有8个单词:He said ths s not a good idea
这是本人自己写的可是不对,求帮看看
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ListWords {
public static void main(String[] args) throws IOException {
readkeyboard();

}

public static void readkeyboard() throws IOException {
InputStreamReader str=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(str);
int score = 0;
String st=null;
String[] temp=new String[10];
while(!(st=in.readLine()).equals("quit")){
temp = st.split(" ");
score++;
}
System.out.println("你输入的单词书为"+score+";"+temp);
}
}
在次向各位大神表示感谢
...全文
192 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
rencht 2016-05-16
  • 打赏
  • 举报
回复
两个问题: 1. 照你给的例子,单词之间的分隔符并不只有空格而已;可以用正则:

temp = st.split("[ ,\"'.]+");
2. 你的score统计的是句子的条数。

score += temp.length;
imfang 2016-05-16
  • 打赏
  • 举报
回复
引用 2 楼 jjzzggkk 的回复:
能说的明白点吗?temp = st.split("[ ,\"'.]+");这样写也没办法打印出单词啊
初学,难免没有头绪,多看看别人的程序,多理解:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
	public static void main(String[] args) throws IOException  {
		InputStreamReader str = new InputStreamReader(System.in);
		BufferedReader in = new BufferedReader(str);
		String st = null;
		Set<String> set = new HashSet<>();
		Pattern pattern = Pattern.compile("(?i)[a-z]+");
		Matcher m = null;
		while (!(st = in.readLine()).equals("quit")) {
			m = pattern.matcher(st);
			while (m.find())set.add(m.group());
		}
		in.close();
		System.out.println("你输入的单词数为" + set.size());
		System.out.println(set.toString());
		
	}
}
运行结果:
How are you?
I'm fine, thank you!
quit
你输入的单词数为7
[thank, are, you, m, How, fine, I]
jjzzggkk 2016-05-16
  • 打赏
  • 举报
回复
能说的明白点吗?temp = st.split("[ ,\"'.]+");这样写也没办法打印出单词啊

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧