【发布时间】:2018-12-05 08:59:55
【问题描述】:
我需要创建一个程序来计算文本文件中字符的频率,以及段落单词和句子的数量。
我有一个问题,当我的程序输出字母的频率时,程序会为字母表中的每个字母输出多个输出。
输出应该是这样的:
如果输入是“hello world!”
(应该为所有字母输出这个):
字母a已被找到0次
字母 b 已被找到 0 次
(直到到达出现的字母,然后显示它们出现的次数)
段落数:1
句子数:1
字符数:10
字数:2
我已经为此工作了数周,但仍然找不到解决方案。
package SuperCounter2;
import java.io.*;
public class SuperCounter2 {
public static void main(String[] args) throws IOException {
File file = new File("//Users//4617621//Desktop//This is the most stupid assignment");
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
String line;
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int whitespaceCount = 0;
while ((line = reader.readLine()) != null) {
int ci, i, j, k, l = 0;
char c, ch;
i = line.length();
if (line.equals("")) {
paragraphCount++;
}
if (!(line.equals(""))) {
characterCount += line.length();
String[] wordList = line.split("\\s+");
countWord += wordList.length;
whitespaceCount += countWord - 1;
String[] sentenceList = line.split("[!?.:]+");
sentenceCount += sentenceList.length;
}
int counter = 0;
for (int m = 0; m < line.length(); m++) {
counter++;
}
for (c = 'A'; c <= 'z'; c++) {
k = 0;
for (j = 0; j < i; j++) {
ch = line.charAt(j);
if(ch == c) {
k++;
System.out.println(" the character " + c + " has occured " + k + " times");
}
}
}
}
System.out.println("Total word count = " + countWord);
System.out.println("Total number of sentences = " + sentenceCount);
System.out.println("Total number of characters = " + characterCount);
System.out.println("Number of paragraphs = " + paragraphCount);
System.out.println("Total number of whitespaces = " + whitespaceCount);
}
}
【问题讨论】:
-
这听起来是一个很好的机会让你花一些时间学习how to debug你的代码。
-
你得到的实际输出是什么?
-
您不会在任何地方按字母保存任何信息。
-
字符 s 出现 1 次 字符 s 出现 2 次 字符 s 出现 3 次 字符 s 出现 4 次 它将为字母表中的每个字母输出不止一次。
-
您确定需要分别计算大小写字母吗?如果您要计算字母表中的每个字母,您不认为使用多个计数器会更有效吗?也许是一个计数器数组?
标签: java