简体   繁体   English

计算文本文件中的字符并打印到文本文件

[英]Count characters in text file and print to text file

I want to count the number of each alphabetic character in this text file, unless the line begins with a ">" in which case it will simply write that line to the file. 我要计算此文本文件中每个字母字符的数量,除非该行以“>”开头,在这种情况下,它只会将该行写入文件中。 This is what I have, and it will not compile because it says " error: cannot find symbol " and points to the period in my for-statement line.length . 这就是我所拥有的,它不会编译,因为它说“ error: cannot find symbol ”,并指向我的for语句line.length

Why isn't this working?? 为什么这不起作用?

String line;
while ((line = br.readLine () ) != null)
{
    if (line.startsWith( ">" ))
    {
        line += "\t";
        bw.write (line);
    }
    else
    { 
            int aCounter=0;
            int bCounter=0;
            int cCounter=0;
        for (int m=0; m < line.length; m++)
        {
            char letter = line.charAt(m);


            switch (letter)
            {
                case 'A':
                    aCounter++;
                    break;
                case 'B':
                    bCounter++;
                    break;
                case 'C':
                    cCounter++;
                    break;
            }
            }    
        bw.write( "A:" + aCounter + " B:" + bCounter + " C:" + cCounter);

}

file to be read sample: 要读取的文件样本:

this is a program that will count characters abcdabcdababab 这是一个将计算字符abcdabcdababab的程序

wanted program output: 所需程序输出:

this is a program that will count characters a:5 b:5 c:2 d:2 这是一个程序,将计算字符a:5 b:5 c:2 d:2

它应该是line.length() ,其参数表示方法:

for (int m=0; m < line.length(); m++ )

You must be confused with array's length property and string's length() method. 您必须对数组的length属性和字符串的length()方法感到困惑。 The methods will have to be accessed with () (parenthesis) and the properties can be accessed by just names. 必须使用() (括号)来访问方法,并且仅可以使用名称来访问属性。

UPDATE: You need to initialize the counters above the for loop. 更新:您需要初始化for循环上方的计数器。 They are resetting to 0 in each iteration of the loop. 在循环的每次迭代中,它们都将重置为0。

int Acounter=0; int Bcounter=0; int Ccounter=0;

these should be above the for loop.Another suggestion is, in java variables has to start with a lower case letter (and classes should start with upper case letter). 另一个建议是,在Java变量中,必须以小写字母开头(类应以大写字母开头)。 Ex: ACounter should be aCounter . 例如: ACounter应该是aCounter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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