I ran it with a txt file (I read a file name from the console when I tested it instead) with the following in it:
a dkj aa po kk e ??? ? !
The output was:
8
! 1
a 3
d 1
e 1
j 1
k 3
? 4
o 1
So it's calculated the frequency correctly, so I'm not sure why that condition hasn't passed.
I don't know why it's sorted everything except "?" into ascending order either
package com.codegym.task.task18.task1821;
import java.io.*;
import java.util.*;
/*
Symbol frequency
*/
public class Solution {
public static void main(String[] args) throws Exception{
String fileName = args[0];
FileInputStream fileInputStream = new FileInputStream(fileName);
ArrayList<Integer> symbols = new ArrayList<>();
//read file and add all bytes to list
while (fileInputStream.available()>0){
symbols.add(fileInputStream.read());
}
fileInputStream.close();
//sort list into ascending order
Collections.sort(symbols);
//add all symbols and their frequency to HashMap
HashMap<Integer, Integer> symbolsAndFrequency = new HashMap<>();
int frequency = 1;
for(int i = 0; i<symbols.size()-1; i++){
if(symbols.get(i)==symbols.get(i+1)){
frequency++;
}else{
symbolsAndFrequency.put(symbols.get(i), frequency);
frequency=1;
}
}
//display elements of HashMap
for (HashMap.Entry<Integer, Integer> pair : symbolsAndFrequency.entrySet()){
int i = pair.getKey(); //use int so that can be cast to char in next line
System.out.println((char)i+" "+pair.getValue());
}
}
}