我应该创建一个程序来统计文本文件中的单词数和平均字符数(不含空格)。我已经创建了这个程序,我只有一个问题。我的字符总数计数器计算字符"-“和”“。”在计算单词时,我不希望发生这种情况。目前我正在统计300个字符。有四个“。还有一个"-“,它应该从计数器中删除,这样我就可以得到295的总值。我尝试使用char,但遇到不允许我将字符串与char进行比较的错误。我的朋友建议我比较,我应该尝试加入一种比较char和Unicode的方法,但我不知道如何开始编码。
public class Count {
public static void main(String[] args) {
File sFile = new File("s.txt");
FileReader in;
BufferedReader readFile;
String sourceCode;
int amountOfWords = 0;
int amountOfChars = 0;
try {
in = new FileReader(sFile);
readFile = new BufferedReader(in);
while ((sourceCode = readFile.readLine()) != null) {
String[] words = sourceCode.split(" ");
amountOfWords = amountOfWords + words.length;
for (String word : words) {
amountOfChars = amountOfChars + word.length();
}
}
System.out.println("Amount of Chars is " + amountOfChars);
System.out.println("Amount of Words is " + (amountOfWords + 1));
System.out.println("Average Word Length is "+ (amountOfChars/amountOfWords));
readFile.close();
in.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist or could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}
发布于 2018-02-22 00:43:38
在做之前
String[] words = sourceCode.split(" ");
使用replace
去掉所有不需要的字符
例如:
sourceCode = sourceCode.replace ("-", "").replace (".", "");
String[] words = sourceCode.split(" ");
发布于 2018-02-22 01:17:41
或者,您可以使用全部3个字符"“、”“。”还有";“我猜是在散落的地方。
发布于 2018-02-22 01:46:05
这是你问题的答案。
public static int numberOfWords(File someFile) {
int num=0;
try {
String line=null;
FileReader filereader=new FileReader(someFile);
try (BufferedReader bf = new BufferedReader(filereader)) {
while((line=bf.readLine()) !=null) {
if (!line.equals("\n")) {
if (line.contains(" ") {
String[] l=line.split(" ");
num=num+l.length;
} else {
num++;
}
}
}
}
} catch (IOException e) {}
return num;
}
public static int numberOfChars(File someFile) {
int num=0;
try {
String line=null;
FileReader filereader=new FileReader(someFile);
try (BufferedReader bf = new BufferedReader(filereader)) {
while((line=bf.readLine()) !=null) {
if (!line.equals("\n")) {
if (line.contains(" ") {
String[] l=line.split(" ");
for (String s : l) {
s=replaceAllString(s, "-", "");
s=replaceAllString(s, ".", "");
String[] sp=s.split("");
num=num+sp.length;
}
} else {
line=replaceAllString(line, "-", "");
line=replaceAllString(line, ".", "");
String[] sp=line.split("");
num=num+sp.length;
}
}
}
}
} catch (IOException e) {}
return num;
}
public static String replaceAllString(String s, String c, String d){
String temp = s.replace(c ,d);
return temp;
}
https://stackoverflow.com/questions/48917826
复制相似问题