How do I count the frequency of an item in a given range?

116 Views Asked by At

I've been given a lab where I'm supposed to create a program that reads a file with 1000 random integers between 10 to 59 inclusive and generate a frequency table like this:

enter image description here

The ranges are 10 to 19, 20 to 29, 30 to 39, 40 to 49, and 50 to 59. Here is a sample from the RandomInt.txt: 50 11 55 12 20 13 53 34 19 39 58 58 24 59 28 10 52 18 55 59 28 29 54

I've been successful at reading all the integers in a file, but for some reason my result for the frequency part is just 1 for every category. How do I put each integer in a range and count them all together within that range? So far, here is my updated code that counts the frequency of each integer:

import java.io.*;
import java.util.*;

public class Demo3 
{
    public static void main(String[] args) throws FileNotFoundException 
    {
        File file = new File("RandomInt.txt");
        Scanner sc = new Scanner(file); 
        SequentialSearchST<String, Integer> st = new SequentialSearchST<String, Integer>();
        
        
        int dataSet = 0;
        while(sc.hasNext())
        {
            String key = sc.next();
            dataSet++;
            
            if(st.contains(key))
            {
                st.put(key, st.get(key) + 1);
            }
            else
            {
                st.put(key, 1);
            }
        }
        
        for (String s : st.keys())
        {
            System.out.println("Integer: " + s + " Frequency: " + st.get(s));
        }
        System.out.println("Data Set Size: " + dataSet);
        
    }

}

1

There are 1 best solutions below

3
g00se On

As @user16320675 says, you should probably do something numeric with arrays. See the following as a fairly kludgy fix as the use of strings for something essentially numeric is not really appropriate. Instead of just st.contains(key) you could call st.contains(keyInRange(key)) - the following:

public static String keyInRange(String key) {
    final String[] RANGES = {
        "",
        "10 to 19",
        "20 to 29",
        "30 to 39",
        "40 to 49",
        "50 to 59"
    };
    return RANGES[Integer.parseInt(key) / 10];
}

but beware, because you're currently putting in all ranges irrespective of key for some reason.