Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java counting capital letters in a text file

I am creating a text analyzer using java, what I'm trying to do is to search through the text document, and count how many Capital letter there are.

public static void main(String[] args) {
    Scanner sc = new Scanner(CapitalCount.class.getResourceAsStream("test.txt"));
    String s = sc.nextLine();
    int upperCaseCount = 0;
    int linecount = 0;

    while (sc.hasNextLine()) {
        sc.nextLine();
        linecount++;
    }

    for (int i = 0; i < s.length(); i++) {
        for (char c = 'A'; c <= 'Z'; c++) {
            if (s.charAt(i) == c) {
                upperCaseCount++;

            }
        }
    }
    System.out.println(upperCaseCount + "");
}
}

I think that i will have to do some sort of count on how many lines there are, this is why i have added a line count at the top, although I am unsure on how to implement this with the capital count that only works on the first line.


1 Answers

  1. Scan through every characters
  2. Check if the characters are within Capital Letters Range.

You don't need CapitalCount class to scan a file.

Below is my working solution:

public static void main(String[] args) {
    Scanner sc = null;
    try {
        sc = new Scanner(new File("test.txt"));
        int count = 0;
        while(sc.hasNext()){
            String line = sc.nextLine();
            for(int i = 0 ; i < line.length(); i++){
                if(line.charAt(i) >= 'A' && line.charAt(i) <= 'Z'){
                    count ++;
                }
            }
        }
        System.out.println("The number of capital letters are : "+count);

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
    finally{
        sc.close();
    }

}
like image 181
Prashant Ghimire Avatar answered May 13 '26 00:05

Prashant Ghimire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!