user3020412
user3020412

Reputation: 31

How to Detect the Vowels and Consonants in my program

    String text;
    System.out.print ("Enter a String:");
    text = console.nextLine();

    int spaces = 0;
    int consonants = 0;
    int vowelcount = 0 ;

    for (int index = 0; index < text.length(); index++) {
    char letters = text.charAt(index);


    if (letters == 'A' || letters == 'a')
        vowelcount++;



    else if (letters != 'a' && letters != 'e' && letters != 'i' && letters != 'o' && letters != 'u')
        consonants++;

    }


        System.out.println ("Vowels:" + vowelcount  + "\nConsonants :" + consonants + "\nSpaces : " + spaces);

Sample Output String: Hannah Last Portion of Output Vowels Detected: a a Consonants Detected: h n n h

Upvotes: 0

Views: 41617

Answers (9)

nivedha
nivedha

Reputation: 1

void main() {
  String str = "Cat cat cat";
  print(str.length);
  int vCount = 0;
  var cCount = 0;

  //Converting entire string to lower case to reduce the comparisons
  var str1 = str.replaceAll(" ", "");
  str1.toLowerCase();

  for (int i = 0; i < str1.length; i++) {
    //Checks whether a character is a vowel
    if (str1[i] == 'a' ||
        str1[i] == 'e' ||
        str1[i] == 'i' ||
        str1[i] == 'o' ||
        str1[i] == 'u') {
      //Increments the vowel counter
      vCount++;
    } else if (str1[i].compareTo(str1) != 0) {
      //Increments the consonant counter
      cCount++;
    }

    //Checks whether a character is a consonant

  }
  print("Number of vowels: ${vCount}");
  print("Number of Consonant: ${cCount}");
}

Upvotes: 0

Hiago Balbino
Hiago Balbino

Reputation: 11

I needed to do this function using 'loops for', follow the example in JavaScript:

const defaultListVowels = ['a', 'e', 'i', 'o', 'u'];

function isVowel(value) {
    return defaultListVowels.indexOf(value) >= 0;
}

function printLetters(values) {
    console.log(values + '\r');
}

function vowelsAndConsonants(s) {
    var consonants = [];
    var vowels = [];

    for (let letter of s) {
        if (isVowel(letter)) {
            vowels.push(letter);
        } else {
            consonants.push(letter);
        }
    }

    vowels.forEach(printLetters);
    consonants.forEach(printLetters);
}

Upvotes: 0

shane
shane

Reputation: 171

This example is a Class that reads text from a file as a String, stores this text as a char array, and itterates each element of the array converting the element to a String and seeing if it matches a consonant regex or a vowel regex. It increments the consonantCount or vowelCount depending on the regex match and finally prints out the counts.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;

public class CountVowlesAndConsonants {

public static void main (String [] args) throws IOException{
    CountVowlesAndConsonants countVowlesAndConsonants = new CountVowlesAndConsonants();
    countVowlesAndConsonants.countConsonatsAndVowles("/Users/johndoe/file.txt");

}
public void countConsonatsAndVowles(String file) throws IOException {
     String text = readFile(file);
     Pattern c = Pattern.compile("^(?![aeiouy]+)([a-z]+)$");
     Pattern v = Pattern.compile("^[aeiouy]+$");

     int vowelCount = 0;
     int consonantCount = 0;

     char [] textArray = text.toLowerCase().toCharArray();
     for( char textArraz : textArray ){
         String s = String.valueOf(textArraz);
         if(c.matcher(s).matches()) {
             consonantCount++;
         } else if (v.matcher(s).matches()) {
             vowelCount++;
         }
     }

     System.out.println("VowelCount is " + vowelCount + " Constant Count " + consonantCount);
}

public String readFile(String file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader (file));
    String         line = null;
    StringBuilder  stringBuilder = new StringBuilder();

    try {
        while((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    } finally {
        reader.close();
    }
}
}

Upvotes: 0

shashi
shashi

Reputation: 1

Using LinkedHashSet since it preserves the order and does not allow duplicates

//Check for vowel
public static boolean isVovel(char c) {

    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
        return true;
    }
    return false;
}

public static void main(String[] args) {
    String input = "shashi is a good boy";

    char inter;
    String vov = "";
    String con = "";
    String inp;
    int len = input.length();

    LinkedHashSet<String> vovels = new LinkedHashSet<String>();
    LinkedHashSet<String> consonents = new LinkedHashSet<String>();

    for (int i = 0; i < len; i++) {
        inter = input.charAt(i);
        inp = Character.toString(inter);

        if (isVovel(inter)) {
            vov = Character.toString(inter);
            vovels.add(vov);
        } 
        else {
            con = Character.toString(inter);
            consonents.add(con);
        }
    }
    Iterator<String> it = consonents.iterator();

    while (it.hasNext()) {
        String value = it.next();
        if (" ".equals(value)) {
            it.remove();
        }
    }
    System.out.println(vovels);
    System.out.println(consonents);
}

Upvotes: 0

Actiwitty
Actiwitty

Reputation: 1242

Here is a simple way of doing this, Re-posting my answer from How to count vowels and consonants

public static void checkVowels(String s){
    System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
    //Also eliminating spaces, if any for the consonant count
    System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}

Upvotes: 0

To detect vowels and consonants you need an array for CONSONANTS chars and then check if a char is in this array. Here you can see a working example, it counts consonants, vowels and spaces: import java.io.Console;

public class Vowels
{
    public static final char[] CONSONANTS =
    {
        'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
    };

    public static final char SPACE = ' ';

    public static char[] getConsonants()
    {
        return CONSONANTS;
    }

    public static boolean isConsonant(char c)
    {
        boolean isConsonant = false;
        for (int i = 0; i < getConsonants().length; i++)
        {
            if (getConsonants()[i] == c)
            {
                isConsonant = true;
                break;
            }
        }
        return isConsonant;
    }

    public static boolean isSpace(char c)
    {
        return SPACE == c;
    }

    public static void main(String[] args)
    {
        int spaces     = 0;
        int consonants = 0;
        int vowelcount = 0;

        Console console = System.console();
        console.format("Enter a String:");

        String text = console.readLine();;

        for (int index = 0; index < text.length(); index++)
        {
            char letter = text.charAt(index);
            if (!isSpace(letter))
            {
                if (isConsonant(letter))
                {
                    consonants++;
                }
                else
                {
                    vowelcount++;
                }
            }
            else
            {
                spaces++;
            }
        }

        System.out.println("Vowels:" + vowelcount + "\nConsonants :" + consonants + "\nSpaces : " + spaces);
    }
}

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 209052

Here are a couple help methods

public static boolean isVowel(char c){
    String vowels = "aeiouAEIOU";
    return vowels.contains(c);
}

public static boolean isConsanant(char c){
    String cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return cons.contains(c);
}

Use them here

char c = line.charAt(i);
int vowelCount = 0;
int consanantCount = 0;
int space = 0;
int punctuation = 0;

if (isVowel(c))
    vowelCount++;
else if (isConsanant(c))
    consanantCount++;
else if (Character.isWhitepace(c))
    space++;
else
    punctuation++;

Upvotes: 5

NP83
NP83

Reputation: 182

You could use a regex ex:

  • White spaces: (?\s+)
  • Vowels: (?[aeijo]+)

I guess the next one should be easy ;)

Then use the group match functionality and count all instances

(I most times use a regex tool while building the regex e.g. http://gskinner.com/RegExr/)

Upvotes: 0

Bohemian
Bohemian

Reputation: 425198

Just use regex, and it only takes you one line count:

int spaces = text.replaceAll("\\S", "").length();
int consonants = text.replaceAll("(?i)[\\saeiou]", "").length();
int vowelcount = text.replaceAll("(?i)[^aeiou]", "").length();

These all replace chars not matching the target character type with a blank - effectively deleting them - then using String.length() to give you the count.

Upvotes: 0

Related Questions