How do I calculate the frequency of a given number from a file in java?

How do I calculate the frequency of a given number from a file?

For example if my txt file has the numbers 1 1 2 3 4 4 4

I want to print out how many times the number 1 occurs (1 occurs 2 times) or how many times the number 4 (4 occurs 3 times) occurs.

1 thought on “How do I calculate the frequency of a given number from a file in java?”

  1. new Scanner(new File("/path/to/inputfile.txt")) gets you a scanner. you can call .nextInt() on this to keep pulling numbers from it.

    You can then just make an array that holds the counts for each number; alternatively, you may instead make a Map<Integer, Integer> mapping your number (e.g. 1), to how often it occurs. That’s more complicated, but works well if your numbers can be extremely large.

    That’s all you need. SO is not a ‘do my homework for me’ kind of site, but these hints should be all you need to get to it 🙂

    Reply

Leave a Comment