Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
36
Task/Letter-frequency/Java/letter-frequency-2.java
Normal file
36
Task/Letter-frequency/Java/letter-frequency-2.java
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
public static void main(String[] args) throws IOException {
|
||||
Map<Integer, Integer> frequencies = frequencies("src/LetterFrequency.java");
|
||||
System.out.println(print(frequencies));
|
||||
}
|
||||
|
||||
static String print(Map<Integer, Integer> frequencies) {
|
||||
StringBuilder string = new StringBuilder();
|
||||
int key;
|
||||
for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) {
|
||||
key = entry.getKey();
|
||||
string.append("%,-8d".formatted(entry.getValue()));
|
||||
/* display the hexadecimal value for non-printable characters */
|
||||
if ((key >= 0 && key < 32) || key == 127) {
|
||||
string.append("%02x%n".formatted(key));
|
||||
} else {
|
||||
string.append("%s%n".formatted((char) key));
|
||||
}
|
||||
}
|
||||
return string.toString();
|
||||
}
|
||||
|
||||
static Map<Integer, Integer> frequencies(String path) throws IOException {
|
||||
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(path))) {
|
||||
/* key = character, and value = occurrences */
|
||||
Map<Integer, Integer> map = new HashMap<>();
|
||||
int value;
|
||||
while ((value = reader.read()) != -1) {
|
||||
if (map.containsKey(value)) {
|
||||
map.put(value, map.get(value) + 1);
|
||||
} else {
|
||||
map.put(value, 1);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue