/ Backend Development

Count the occurrences of 'b' and 'k' in an input String in Java

Creator Image
Bashar Alshaibani
15 Apr 2024 -
4 min Reading time
public class Main {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String word = input.nextLine();
        int countK = 0;
        int countB = 0;

        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
            if(c == 'b'){
                countB++;
            } else if (c == 'k'){
                countK++;
            }
        }

        String category;

        if(countB == 0 && countK == 0){
            category = "none";
        } else if (countB > countK){
            category = "boba";
        } else if (countK > countB){
            category = "kiki";
        } else {
            category = "boki";
        }
        System.out.println(category);
    }

}

How It Works:

Input Handling: It starts by creating a Scanner to read a string from the user. The user is expected to enter a word that only contains lowercase letters ('a' to 'z').

Counting 'b' and 'k': The program then iterates through each character in the string, incrementing countB if the character is 'b' and countK if it's 'k'.

Category Determination:

If both counts are zero (countB == 0 && countK == 0), the word is categorized as "none". If countB is greater than countK, the word is a "boba" word. If countK is greater than countB, it's a "kiki" word. If the counts are equal, it's a "boki" word.

Output: Finally, the program prints the determined category.