But when testing my program, it never repeated the same byte for me.
Some test cases:
INPUT FILE: OUTPUT:
abccd 99
abcdAABCD 65
a
b
c
d
e 10 13 // these two are the bytes of the end of the lines, so also that's OK in my opinion.
aaabbbcccddd 97 98 99 100 // each byte occurs equally often, so each byte is displayed.
Maybe the problem with the validation again is that I'm using static variables in the program?... (This has caused problems before, even though the program worked perfectly.)
package com.codegym.task.task18.task1803;
import java.io.*;
import java.util.*;
/* Most frequent bytes */
public class Solution {
// this map will store the read bytes from the file.
// keys=the read bytes, values=number of occurrences
public static Map<Integer, Integer> fileBytes = new HashMap<>();
public static Integer highestValue = 0; // the highest occurrence
// If multiple bytes have the same highest occurrence, this list will store those bytes:
public static ArrayList<Integer> resultList = new ArrayList<>();
public static void main(String[] args) throws Exception {
readFileToMap();
lookingForHighestValue();
lookingForRepeatingValue();
printResults();
}
public static void readFileToMap() throws Exception {
BufferedReader inputConsole = new BufferedReader(new InputStreamReader(System.in));
String fileName = inputConsole.readLine();
inputConsole.close();
BufferedInputStream inputFromFile = new BufferedInputStream(new FileInputStream(fileName));
while (inputFromFile.available()>0) {
Integer byteRead = inputFromFile.read();
// If this read byte already exists in the map, it will overwrite that entry, increasing its value by 1:
if (fileBytes.containsKey(byteRead)) {
fileBytes.replace(byteRead, fileBytes.get(byteRead)+1);
}
else fileBytes.put(byteRead, 1);
}
inputFromFile.close();
}
public static void lookingForHighestValue() {
for (Integer val : fileBytes.values() ) {
if (val.compareTo(highestValue) > 0) {
highestValue = val;
}
}
}
public static void lookingForRepeatingValue() {
for (Map.Entry<Integer, Integer> pair : fileBytes.entrySet() ) {
if (pair.getValue().equals(highestValue)) {
resultList.add(pair.getKey());
}
}
}
public static void printResults() {
int count = 0;
for( Integer textByte : resultList) {
count++;
System.out.print(textByte);
if (count<resultList.size()) System.out.print(" ");
}
}
}