简体   繁体   中英

How to count how many times a number appears in a .txt file

Good morning,

I'm doing some Java exercises and stumbled upon this question. I have a .txt file with several numbers, one per line. The goal of the exercise is to see which numbers are equal to 10^0, ... , 10^n until reach n. Then, i have to write in a .txt how many times each one of then appears. So i have a file with:

1 100 100 100 10 1 1

And i need to write:

1 - 10 3 - 1 3 - 100

I can read the file, check then number and print then. I just can't figure how to make a counter than stays correct. Any help?

Here is the piece of code:

// TODO - Count how many time a number appears.
public static void numberOfTimes (BufferedReader in, BufferedWriter out, int n)        throws IOException {

        String s;
    int i;
    int counter = 0;

    while ((s = in.readLine()) != null) {
        i = Integer.parseInt(s);
        for (int j = 0; j <= n; j++) {
            if (i == Math.pow(10, j)) {
                counter++;
                out.write(Integer.toString(counter) + " " + Integer.toString(i) + "\n");
            }
        }
    }
}

Since there are multiple counts to keep track of, a single integer counter is clearly not going to suffice.

One possibility is to use Map<Integer,Integer> for the counts. Since this is homework, I leave it to you to figure out the details.

Another possibility is to use an array of counts, and use log10(i) as the index into the array. In other words, the count for 10^k will be stored at the k -th position in the array. Hint: In your code, you are already indirectly computing log10(i) .

Since you are dealing with Integer you can preload a Map<Integer,Integer> with all the values less than Integer.MAX (2,147,483,647).

The Map will need all values from 10^0,10^1,...,10^9 as the keys (this is ten (10) keys in total) . What you then do is perform a boolean check on the value you are reading in, if it matches one of these keys increment the value of that key by 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM