简体   繁体   中英

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 .

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

wanted program output:

this is a program that will count characters 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. 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. They are resetting to 0 in each iteration of the loop.

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). Ex: ACounter should be aCounter .

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