How to not count special character and vowels occurences in string length using user input

714 views Asked by At

I just got into my 2nd programming subject but my prof just throws stuff at us that he didn't teach so I'm guessing that I need help from people because searching the internet's help ain't enough

So the output that I'm looking for is like this

Enter word : #$nsaei!
result = 2
2

There are 2 answers

1
Sash Sinha On

Try something like this using a Scanner, converting the String input into a char array using toCharArray() and checking each char using isLetterOrDigit and checking if the character is not in "AEIOUaeiou" using indexOf() and therefore not a vowel:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Please enter a word:");
    String input = sc.nextLine();

    int consonantOrDigits = 0;
    for(char c : input.toCharArray()) {
      if(Character.isLetterOrDigit(c) && "AEIOUaeiou".indexOf(c) == -1)
        consonantOrDigits++;
    }

    System.out.println(consonantOrDigits);
  }
}

Try it here!

4
Nurjan On

You can do it this way:

System.out.println("Enter word: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

int count = 0;

for (int i = 0; i < input.length(); i++) {
    if (String.valueOf(input.charAt(i)).matches("^[a-zA-Z0-9&&[^aeuio]]*$")) {
        count++;
    }
}

System.out.println("result: " + count);

Hope this helps.