如何跟踪多个计数器变量

时间:2011-09-13 20:46:57

标签: java

我编写了一些代码来计算来自未知数量文件的“if”语句的数量。如何将每个文件的计数分开,并从所有文件中总计“if”?

代码:

import java.io.*;

public class ifCounter4 
{
    public static void main(String[] args) throws IOException
    {
        // variable to keep track of number of if's
        int ifCount = 0;

        for (int c = 0; c < args.length; c++)
        {
            // parameter the TA will pass in
            String fileName = args[c];

            // create a new BufferReader
            BufferedReader reader = new BufferedReader( new FileReader (fileName));
            String line  = null;
            StringBuilder stringBuilder = new StringBuilder();
            String ls = System.getProperty("line.separator");

            // read from the text file
            while (( line = reader.readLine()) != null) 
            {
                stringBuilder.append(line);
                stringBuilder.append(ls);
            }

            // create a new string with stringBuilder data
            String tempString = stringBuilder.toString();

            // create one last string to look for our valid if(s) in
            // with ALL whitespace removed
            String compareString = tempString.replaceAll("\\s","");

            // check for valid if(s)
            for (int i = 0; i < compareString.length(); i++)
            {
                if (compareString.charAt(i) == ';' || compareString.charAt(i) == '}' || compareString.charAt(i) == '{') // added opening "{" for nested ifs :)
                {
                    i++;

                    if (compareString.charAt(i) == 'i')
                    {
                        i++;

                        if (compareString.charAt(i) == 'f')
                        {
                            i++;

                            if (compareString.charAt(i) == '(')
                                ifCount++;
                        } // end if
                    } // end if
                } // end if

            } // end for

         // print the number of valid "if(s) with a new line after"
         System.out.println(ifCount + " " + args[c]);  // <-- this keeps running total
                                                       // but not count for each file
        }

        System.out.println(); 

    } // end main
} // end class 

5 个答案:

答案 0 :(得分:2)

您可以创建一个Map,将文件名存储为键,将计数存储为值。

Map<String, Integer> count = new HashMap<String, Integer>();

在每个文件之后

count.put(filename, ifCount);
ifcount = 0;

将值设置为总数。

答案 1 :(得分:0)

使用文件名作为键的Map如何将ifs的数量保持为值?对于整体计数,将其存储在自己的int中,或者在需要时通过将Map中的所有值相加来计算它。

Map<String, Integer> ifsByFileName = new HashMap<String, Integer>();
int totalIfs = 0;
for each if in "file" {
    totalIfs++;
    Integer currentCount = ifsByFileName.get(file);
    if (currentCount == null) {
        currentCount = 0;
    }
    ifsByFileName.put(file, currentCount + 1);
}

// total from the map:
int totalIfsFromMap = 0;
for (Integer fileCount : ifsByFileName.values()) {
    totalIfsFromMap += fileCount;
}

答案 2 :(得分:-1)

使用数组可以解决这个问题。

int[] ifCount = new int[args.length]; 然后在你的循环中ifCount[c]++;

答案 3 :(得分:-1)

在这种情况下出现问题的是许多线程想要增加同一组计数器

ifCount[c]++;ifsByFileName.put(file, currentCount + 1);等操作不是线程安全的

使用ConcurrentMapAtomicLong的明显解决方案也不够,因为您必须将初始值设置为0,这需要额外的锁定。

Google Guava项目提供了方便的开箱即用解决方案:AtomicLongMap

通过这门课你可以写:

AtomicLongMap<String> cnts = AtomicLongMap.create();

cnts.incrementAndGet("foo");
cnts.incrementAndGet("bar");
cnts.incrementAndGet("foo");

for (Entry<String, Long> entry : cnts.asMap().entrySet()) {
    System.out.println(entry);
}

打印:

foo=2
bar=1

完全是线程安全的。

答案 4 :(得分:-1)

这是一个增加到100的计数器,如果你编辑N的值,它会在*的倍数旁边放一个*。

公共类SmashtonCounter_multiples {

 public static void main(String[] args) {


    int count;
    int n = 3; //change this variable for different multiples of

    for(count = 1; count <= 100; count++) {
        if((count % n) == 0) {
                System.out.print(count + "*");
                }   
        else {
                System.out.print(count);

        if (count < 100) {
        System.out.print(",");
    }
    } 
    }

}