0

I have this program and I need it to count the lower and uppercase A's in a data file. I'm not sure what to use between charAt or substring. It's also all in a while loop, and I was getting at the fact that maybe I need to use the next() method? Maybe? I just need to find these characters and count them up in total.

import static java.lang.System.*;
import java.util.*;
import java.io.*;

public class Java2305{
    public static void main(String args[]){
        new Solution();
}}


class Solution
{
    private Scanner fileScan;

    Solution()
    {
        run();
    }

    void run()
    {
        int count = 0;

        try
        {
            fileScan = new Scanner(new File("letters01.dat"));

            while(fileScan.hasNext() )
            {
                String getA = fileScan.substring("A");
                out.println(getA);
                count++;
            }




        }
        catch(Exception e){}

        out.println();
        out.println("The letter 'A' occurs "+count+" times.");
        out.println();
        out.println();
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Dommy Bomb
  • 15
  • 5

1 Answers1

0

Why are you using Scanner? That is meant for scanning text for delimited tokens using regular expressions, but you are not really using that.

I suggest you use a Reader instead, then you can call its read() method to read individual characters:

int count = 0;

try
{
    Reader fileReader = new FileReader("letters01.dat");
    /* or:
    Reader fileReader = new InputStreamReader(
        new FileInputStream("letters01.dat"),
        "the file's charset here"
    ); 
    */

    int value = fileReader.read();
    while (value != -1)
    {
        char ch = (char) value;
        if ((ch == 'a') || (ch == 'A'))
            count++;
        value = fileReader.read();
    }
}
catch(Exception e){}

You can use a BufferedReader to read the file more efficiently:

Reader fileReader = new BufferedReader(new FileReader("letters01.dat"));
/* or:
Reader fileReader = new BufferedReader(
    new InputStreamReader(
        new FileInputStream("letters01.dat"),
        "the file's charset here"
    )
); 
*/

And then optionally process it line-by-line instead of char-by-char (though you can still do that, too):

int count = 0;

try
{
    String line = fileReader.readLine();
    while (line != null)
    {
        for(int i = 0; i < line.length(); ++i)
        {
            char ch = line.charAt(i);
            if ((ch == 'a') || (ch == 'A'))
                count++;
        }
        line = fileReader.readLine();
    }
}
catch(Exception e){}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770