如何计算数字出现在.txt文件中的次数 [英] How to count how many times a number appears in a .txt file

查看:169
本文介绍了如何计算数字出现在.txt文件中的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,

我正在做一些Java练习并偶然发现了这个问题。我有一个包含多个数字的.txt文件,每行一个。练习的目的是看到哪些数字等于10 ^ 0,...,10 ^ n直到达到n。然后,我必须用.txt写出每一个出现的次数。
所以我有一个文件:

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

1 100 100 100 10 1 1

我需要写:

1 - 10
3 - 1
3 - 100

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?

这是一段代码:

// 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.

一种可能性是使用 Map< Integer,Integer> 计数。由于这是家庭作业,我留给你弄清楚细节。

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.

另一种可能性是使用一组计数,并使用 log10 (i)作为数组的索引。换句话说, 10 ^ k 的计数将存储在数组中的 k -th位置。 提示:在您的代码中,您已经间接计算 log10(i)

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).

这篇关于如何计算数字出现在.txt文件中的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆