我正在尝试编写一个字母频率程序,用于计算.txt文件中的字母字符,并将频率数据显示在2列表中。我正在努力从函数processFile中调用函数char2int。我不确定是否需要使用if语句。另外,我总结了所有字母字符和其他字符。如果有人可以帮助解释我做错了什么,我将不胜感激。
这是我的代码:
final static int AlphabetSize = 26;
final static Scanner cin = new Scanner(System.in);
final static PrintStream cout = System.out;
final static int MaxBarLength = 50;
public static void main(String[] args) {
String fileName;
// get the file name
cout.print("Enter the file name: ");
fileName = cin.nextLine();
// process the file
try {
processFile(fileName);
}
catch (IOException e) {
e.printStackTrace();
} // end try
} // end main
static void processFile(final String fileName)
throws FileNotFoundException, IOException
{
FileInputStream inFile = new FileInputStream(fileName);
int inputValue;
// declare other variables you need
int counters [] = new int [26];
int alpha = 0;
int num = 0;
int ticker = 0;
// get the first character from file
inputValue = inFile.read();
while (inputValue != -1) {
char ch = (char) inputValue;
// add code to process this character
if (){
counters[char2int(ch)]++;
alpha++;
}else{
num++;
}
// read next input character
inputValue = inFile.read();
} // end loop
inFile.close();
System.out.println("\nThe data file has " + alpha + " alphabetic, and " + num + " other characters.\n");
// generate appropriate output
display(counters);
} // end function
static void display(final int [] counters) {
// write code for this function
System.out.println("Letter" + " " + "Count" + " " + "Bar");
System.out.println("------" + " " + "-----" + " " + "---");
printChars(counters);
} // end function
// char2int is complete
static int char2int(final char arg) {
if (!Character.isLetter(arg))
return -1;
else
return (int) Character.toUpperCase(arg) - (int) 'A';
} // end function
// function printChars writes n copies of the character c to the
// standard output device
static void printChars (final int[] counters) {
// write the code
for (int i = 0; i < 26; i++){
System.out.printf("%c%7d\n", i + 'A', counters[i]);
}
// end printChars
} // end function
答案 0 :(得分:0)
我个人会这样做威廉:
int c = char2int(ch);
if (c >= 0) {
counters[c]++;
alpha++;
}
else { num++; }
如果文本文件中有任何字符,您还应该考虑使用非字母字符。这也可以在 char2int()方法中处理。