📄 statistics.java
字号:
import java.io.FileReader;
import java.io.IOException;
/**
* Counts the letters of a given text file.
* The letters are restricted to a-z, A-Z, 0-9 and SPACE
*/
public class Statistics {
/**
* Counts the letters.
*
* @param filename The name of the textfile
* @return An array of int with the number for each letters
*/
// Space for 26 characters, 10 numbers and SPACE
static int INDEX_ENTRIES=37;
// Index 0-25 for "A-Z" (ASCII 65-90) and "a-z (ASCII 97-122)" ,
static int UPPER_A_ASCII=Character.getNumericValue('A');
static int LOWER_A_ASCII=Character.getNumericValue('a');
static int A_INDEX=0;
static int UPPER_Z_ASCII=Character.getNumericValue('Z');
static int LOWER_Z_ASCII=Character.getNumericValue('z');
static int Z_INDEX=25;
// Index 26-35 for "0-9" (ASCII 48-57)
static int ZERO_ASCII=Character.getNumericValue('0');
static int ZERO_INDEX=26;
static int NINE_ASCII=Character.getNumericValue('9');
static int NINE_INDEX=35;
// Index 36 for SPACE (ASCII 32)
static int SPACE_ASCII=Character.getNumericValue(' ');
static int SPACE_INDEX=36;
public static int[] getStatistics(String filename) {
// little helper
int actChar=0;
int[] stat = new int[INDEX_ENTRIES];
try {
//Open FileReader stream
FileReader fr = new FileReader(filename);
//Read each char until the stream is empty
while ((actChar = fr.read()) != -1) {
if (actChar == SPACE_ASCII)
stat[SPACE_INDEX]++; // SPACE
else if (actChar >= ZERO_ASCII && actChar <= NINE_ASCII) {
stat[actChar + Z_INDEX - ZERO_ASCII]++; // Number!
} else if (actChar >= UPPER_A_ASCII && actChar <= UPPER_Z_ASCII) {
stat[actChar - UPPER_A_ASCII]++; // Uppercase letters!
} else if (actChar >= LOWER_A_ASCII && actChar <= LOWER_Z_ASCII) {
stat[actChar - LOWER_A_ASCII]++; // Lowercase letters!
}
}
// Close the stream
fr.close();
} catch (IOException io) {
io.printStackTrace();
System.err.println("Error opening file " + filename);
}
return stat;
}
// -------------
/**
* Prints out an array with the information of counted letters.
*
* @param stats The array of statistics.
*/
private static void printResults(int[] stats) {
int actChar;
// Only print those chars with hits
for (int i = A_INDEX; i < Z_INDEX; i++) {
if (stats[i] > 0) {
actChar = i + LOWER_A_ASCII + 87;//XXX was ist das f黵 ne zahl?
System.out.println((char) actChar + " = " + stats[i] + ", ");
}
}
// same for numbers...
for (int i = ZERO_INDEX; i < NINE_INDEX; i++)
if (stats[i] > 0) {
actChar = i - Z_INDEX;
System.out.println(actChar + " = " + stats[i] + ", ");
}
// any spaces?
if (stats[SPACE_INDEX] > 0)
System.out.println("SPACE = " + stats[SPACE_INDEX]);
}
// -------------
public static void main(String[] args) {
if (args.length > 0)
printResults(getStatistics(args[0]));
else
throw new IllegalArgumentException(
"No Filename given! Don't know what to parse!");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -