DEV Community

Cover image for I failed to print the consonants
shamnad-sherief
shamnad-sherief

Posted on

I failed to print the consonants

I recently had a coding challenge as part of a recruitment drive, and I was asked to write a program to print the number of consonants in a given string. I was confident in my abilities and decided to use my favourite programming language, Java, to solve the problem.

However, when I ran my code, I encountered an error. I was under a lot of pressure during the coding challenge and my confidence took a hit. I couldn't understand what I had done wrong. I felt embarrassed and ashamed of myself for not being able to solve what seemed like a simple problem.

After the coding challenge, I went home and revisited my code.

public class Consonants {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter a string");
        String str = input.nextLine();
        int len = str.length();
        int count = 0;

        for (int i = 0; i < len; i++){

            char c =  Character.toLowerCase(str.charAt(i));
            if( c != 'a' ||
                    c != 'e' ||
                    c != 'i' ||
                    c != 'o' ||
                    c != 'u' ||
                    c != ' ' ){

                count++;
            }
        }
        System.out.println(count);
    }
}
Enter fullscreen mode Exit fullscreen mode

That's when I realized that I had made a logical mistake in my if statement. Instead of using the && operator, I used the || operator, which caused the program to always evaluate to true.

It was a frustrating experience, but I learned a valuable lesson. In high-pressure situations, our thinking can become more focused and narrow, and it can be difficult to see all the possibilities. That's why it's always a good idea to take a break, relax, and come back to the problem with a fresh mind.

I also learned the importance of double-checking my work and paying attention to details, especially in a coding challenge where mistakes can be costly. This experience has motivated me to keep practising and improving my coding skills so that I can perform better in future coding challenges.

Top comments (0)