编写一个JAVA程序,接受用户输入的一段英文文字,统计出其中的字符个数、单词个数和句子的个数。(设句子以“。”“!”“?”结束,单词之间利用空格分隔)。
- 提问者网友:川水往事
- 2021-07-20 16:57
- 五星知识达人网友:你可爱的野爹
- 2021-07-20 17:39
import java.util.HashMap;
import java.util.Map;
import java.io.*;
public class test{
private static String WORD = "0";
private static String SENTENCE = "1";
public static Map<String, Integer> getCount(String str) {
str = str.replace(".", "#");
str = str.replace("?", "#");
str = str.replace("!", "#");
int wordCount = str.split(" ").length;
int sentenceCount = str.split("#").length;
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(WORD, wordCount);
map.put(SENTENCE, sentenceCount);
return map;
}
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String x=br.readLine();
Map<String, Integer> map = getCount(x);
System.out.println("单词数量: "+map.get(WORD));
System.out.println("句子数量: " + map.get(SENTENCE));
}
}
- 1楼网友:我住北渡口
- 2021-07-20 18:23
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
public class dancitongji {
public static int danci(String str)//计算单词个数 { return str.split(" ").length; } public static int yuju(String str)//计算语句的个数 { int num=1; for(int i=0;i<str.length();i++) { if(str.substring(i, i+1).equalsIgnoreCase(",")|| str.substring(i, i+1).equalsIgnoreCase("!")|| str.substring(i, i+1).equalsIgnoreCase(".")) { num++; } } return num; } public static int zifu(String str)//计算字符的个数 { int num=0; for(int i=0;i<str.length();i++) { if(Character.isLetter(str.charAt(i))) { num++; } } return num; } public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while(true) { try { System.out.println("请输入要检测的语句" ); String str = in.readLine(); System.out.println("次语句共有"+danci(str)+"个单词"); System.out.println("次语句共有"+zifu(str)+"个字母"); System.out.println("次语句共有"+yuju(str)+"句"); } catch (IOException e) { e.printStackTrace(); } } }
}
测试结果: