How to avoid counting the repeated vowel? - java

I have written the code for the first part, but it counts the number of vowels with repetitions included, but I also want to know how to count the number of vowels without repetitions.
Also I am struggling to write the second part of the code, that is, report the sum of vowels.
Here's what I have written so far:
import java.io.*;
public class CountVowel {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
String s = br.readLine();
int l = s.length();
char ch;
int i;
int count = 0;
for(i = 0; i < l; i++)
{
ch = s.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
count=count+1;
}
}
System.out.println("The number of vowels are:"+count);
}
}

Simply, you try with Set interface that not stores any duplicates, use following code,
public static void main(String[] args) throws IOException {
Set<Character> set = new HashSet<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
String s = br.readLine();
int l = s.length();
char ch;
int i;
int count = 0;
for (i = 0; i < l; i++) {
ch = s.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
set.add(ch);
}
}
System.out.println("The number of vowels are:" + set.size());
}

There is a neater way to do this:
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
for(i=0;i<l;i++) {
ch=s.charAt(i);
vowels.remove(ch);
}
System.out.println("The number of vowels are:" + 5-vowels.size());

I suggest to do it like this. This will output the number of vowels as you want without repetition:
int count = 0;
boolean[] vowel = {false, false, false, false, false};
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for(int i=0;i<l;i++) { //This will traverse every letter for the string
ch=s.charAt(i);
for(int j=0; j<5; j++) { //This will search through vowels
//Ff any vowels are matched the count will increase,
//But if they are already matched, count will not increase
if(ch==vowels[j] && !vowel[j]) {
count++;
vowel[j] = true;
}
}
}
System.out.println("The number of vowels are:" + count);

Here is a alternate approach using two arraylists. One contains vowels and other one is empty say charsInString. We can add into the other one if we encounter an vowel which is not present in the charsInString. We can find whether an vowel has been added by using indexOf
List<Character> chars = new ArrayList<Character>(Arrays.asList('a','e','i','o','u'));
List<Character> charsInString = new ArrayList<Character>();
String test = "this is a test string";
for (char a: test.toCharArray()) {
if (chars.indexOf(a) > -1) {
if (charsInString.indexOf(a) == -1) {
charsInString.add(a);
}
}
}
System.out.println(charsInString.size()); //answer is 3
Demo

Related

How to count each uppercase vowels and lowercase vowels in a string? [duplicate]

If a user enters a string: hello there
it should output
Hello has 2 vowels
There has 3 consonants.
I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result
I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work
import java.util.Scanner;
public class Hwk9
{
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
}
public static int numberVowels(String string1)
{
int count = 0;
int vowels = 0;
int consonants = 0;
for (int i = 0; i < string1.length(); i++)
{
char ch = string1.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
}
Here is a simpler way of doing this, hope this helps:
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()));
}
Made something like this hope this helps, this will give vowels,consonants of each word
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
int count = 0;
int vowels = 0;
int consonants = 0;
for (String retval: string1.split(" ")){
for (int i = 0; i < retval.length(); i++)
{
char ch = retval.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
System.out.println(retval.substring(0, 1).toUpperCase() + retval.substring(1)+" has "+vowels+" vowels and "+consonants+" cosonants");
vowels=0;
consonants=0;
}
}
My code without scanner and maybe not very simple, but:
public class Main{
public static void main(String[] args) {
String test = "qwertyYVTA";
test = test.trim();
int vowels = 0;
int consonants = 0;
Pattern patternVow = Pattern.compile("[eyuioa]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherVow = patternVow.matcher(test);
while (matcherVow.find()) {
vowels++;
}
Pattern patternCons = Pattern.compile("[wrtpsdfghjklzxcvbnm]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherCons = patternCons.matcher(test);
while (matcherCons.find()) {
consonants++;
}
System.out.println("Vowels in test String is " + vowels);
System.out.println("Consonants in test String is " + consonants);
}
}
following code will give you vowel and Constonent count
static String VOWEL_GROUP = "AEIOUaeiou";
static String testString = "AAAASHMAIOUAXCCDIOUGGGGA"; // say this is your text
public static void main(String[] args) {
int vovelCount = 0;
int consonantCount = 0;
for (int j = testString.length() - 1; j >= 0; j--) {//outer loop
for (int i = 0; i < VOWEL_GROUP.length(); i++) { //inner loop
if (VOWEL_GROUP.charAt(i) == testString.charAt(j)) {
vovelCount++; //vowel count in text
break;
}else{
consonantCount ++;
}
}
}
System.out.println(vovelCount+" "+ consonantCount);
}
I suggest you;
to create a final vowels array,
define a bool isVowel(char c) function and use it in your if condition.
Here is the simple code for counting the number of vowels using recursion
public static int vowels(String s){
int count =0;
char c;
if(s.length()==0){
return 0;
}
else{
c =s.charAt(0);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
count++;
}
return count+vowels(s.substring(1));
}
}
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards.
import java.util.*;
public class FindVowelsConsonents {
public static void main(String[] args) {
int vowels_count = 0;
int consonents_count = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++){
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else
consonents_count++;
}
System.out.println(vowels_count+ " "+consonents_count);
sc.close();
}
}
As far as I am concerned you can use StringTokenizer:
String text = "dupalo twoja mama";
StringTokenizer tokenizer = new StringTokenizer(text,"aeiuo",false);
int vowels = tokenizer.countTokens();
System.out.println(vowels);
In this case of "text" it will print out 7.
import java.util.Scanner;
//don't use space in between the input string;
class StrRev {
static String Vowels ="aeiouAEIOU";
public static void main(String[] args){
#SuppressWarnings("resource")
Scanner name = new Scanner(System.in);
String nm = name.nextLine();
System.out.println();
int vowel=0;
int consonant=0;
for(int i=0;i<nm.length();i++){
for(int j=0;j<Vowels.length();j++){
if(Vowels.charAt(j)==nm.charAt(i)){
vowel++;
break;
}
}
}
consonant = nm.length()-vowel;
System.out.println("no of Vowels :"+vowel+"\nno of consonant :"+consonant);
}
}

Delivery is not working

In my java code the line String st = sc.nextLine(); is not taking input when the code is running and when instead I use sc.next(); the code works properly can you please tell me why sc.nextLine(); is not working
import java.lang.*;
import java.util.*;
/**?Chef wrote some text on a piece of paper and now he wants to know how
many holes are in the text. What is a hole? If you think of the paper as
the plane and a letter as a curve on the plane, then each letter divides
the plane into regions.For example letters "A", "D", "O", "P","R" divide
the plane into two regions so we say these letters each have one hole.
Similarly, letter "B" has 2 holes and letters such as "C", "E", "F","K"
have no holes. We say that the number of holes in the text is equal to
the total number of holes in the letters of the text.
Help Chef to determine how many holes are in the text.
Input
First line contains a single integer T <= 40, the number of test cases.
T test cases follow. The only line of each test case contains a non-empty
text composed only of uppercase letters of English alphabet. The length
of the text is less then 100. There are no any spaces in the input.
Output
For each test case,output a single line containing number of holes in the corresponding txt
Example
Input:
2
CODECHEF
DRINKEATCODE
Output:
2
5
*/
class Holes {
public static void main(String[] args) {
int i, Testcase;
int holes, space = 0, j;
Scanner sc = new Scanner(System.in);
Testcase = sc.nextInt();
for (i = 0; i < Testcase; i++) {
holes = 0;
space = 0;
String st = sc.nextLine();
if (st.length() < 100) {
char[] letter = st.toCharArray();
for (j = 0; j < st.length(); j++) {
if (letter[j] == ' ') {
space++;
}
}
for (j = 0; j < st.length(); j++) {
if (space == 0) {
if (letter[j] == 'A' || letter[j] == 'D'
|| letter[j] == 'O' || letter[j] == 'P'
|| letter[j] == 'R') {
holes = holes + 1;
}
if (letter[j] == 'B') {
holes = holes + 2;
}
}
}
}
if (st == st.toUpperCase() && space == 0) {
System.out.println(holes);
}
}
}
}
As Nighthacks mentioned, Scanner.nextInt will not advance to the next input (Read https://stackoverflow.com/a/13102066/643500)
Try it this way:
public class Holes {
public static void main(String[] args) {
int holes;
Scanner sc = new Scanner(System.in);
int numberOfCases = sc.nextInt(); // Get input as int - not going to
// advance
String[] testCases = new String[numberOfCases];
String line = sc.nextLine(); // Move to next
for (int i = 0; i < numberOfCases; i++) {
line = sc.nextLine();// Read input as line
testCases[i] = line;
}
sc.close();
for (String aCase : testCases) {
holes = 0;
if (aCase.length() < 100 && !aCase.contains(" ")) {
for (int j = 0; j < aCase.length(); j++) {
char letter = aCase.charAt(j);
if (letter == 'A' || letter == 'D' || letter == 'O'
|| letter == 'P' || letter == 'R') {
holes++;
}
if (letter == 'B') {
holes = holes + 2;
}
}
System.out.println(holes);
}
}
}
}
That's because the [Scanner#nextInt] method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Workaround:
Either fire a blank Scanner#nextLine call after Scanner#nextInt to consume rest of that line including newline
Check this out.

Java phrase guessing game

Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.

Code that needs to print a Scanner string without vowels

I need to write a program that takes a string, and prints out the string text with all the vowels removed, except when a word starts with it.
The code I've written is halfway there, but I cannot figure out why it will not return the whole string and it does not remove all the vowels. Say I input the phrase "Desirable property area". The program prints the string, "Dirlp" instead of "Dsrbl prprty ar "
Can anybody advise on how I can improve the code to make this work? Thank you!
Here is my code:
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
takeOutVowel (text);
System.out.println ();
}
static void takeOutVowel (String s)
{
char ch = s.charAt(0); //character to be printed
System.out.print (ch);
int nextCh = 1; //determines the position of the next character
int increase = 1; //increase is how much i will increase by in the for loop; takes the position of vowels into //consideration so they can be skipped
for (int i = 1; i <= s.length(); i += increase)
{
ch = s.charAt (nextCh);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
nextCh++;
ch = s.charAt (nextCh);
while (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
{
nextCh++;
ch = s.charAt (nextCh);
if (nextCh >= s.length())
{
ch = ' ';
break;
}
}
}
System.out.print (ch);
nextCh++;
ch = s.charAt (nextCh);
if (ch == ' ') //if the previous position was a space, then this will allow for the vowel to be printed
{
System.out.print ("" + ch + s.charAt(nextCh + 1));
nextCh++;
}
increase = nextCh;
}
Thanks for all the answers so far - very helpful! I'm not allowed to use arrays or anything not covered yet, so I've amended the code to what it is below. It compiles fine but when I run the program and enter the Scanner text, I get a message that says
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 27
at java.lang.String.charAt(String.java:686)
at Vowels.noVowels(Vowels.java:20)
at Vowels.main(Vowels.java:11)
I can't figure what the problem is now. Thank you again for all the help!
import java.util.*;
class Vowels
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
System.out.println (noVowels(text));
}
static String noVowels (String s)
{
String noVowels = "" + s.charAt(0); //Starts a new string with the first character of the input text
for (int i = 1; i <= s.length(); i++)
{
if (isVowel(s.charAt(i)) && s.charAt(i-1) != ' ') //if the character is a vowel and it's previous character wasn't a space, then this is a vowel to be replaced
{
noVowels = noVowels.concat("");
}
else
{
noVowels = noVowels.concat("" + s.charAt(i));
}
}
return noVowels;
}
static boolean isVowel (char ch)
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
return true;
}
else
{
return false;
}
}
}
You can solve this problem easily. Iterate over String and check the vowel. If no vowel than append the result. Try
static void takeOutVowel(String s) {
StringBuilder res = new StringBuilder();
String[] words = s.split(" +");
for (String word : words) {
res.append(word.charAt(0)); //Skip the first char
for (int i = 1; i < word.length(); i++) {
char ch = word.charAt(i);
if (!isVowel(ch)) { // Check the vowel
res.append(ch);
}
}
res.append(' ');
}
System.out.println(res);
}
static boolean isVowel(char ch){
ch=Character.toLowerCase(ch); // Make it case-insensitive.
return ch=='a' ||ch=='e' ||ch=='i' ||ch=='o' ||ch=='u';
}
You can do this easily with a regular expression as well. The first example demonstrates how to simply remove vowels.
public static void main(String[] args)
{
String noVowels = takeOutVowel("Hello how are you?");
System.out.println(noVowels); // prints "Hll hw r y?"
}
// This will remove all vowels from any String
private static String takeOutVowel(String s)
{
return s.replaceAll("[aeiou]", "");
}
But now to satisfy your requirement of ignoring the first letter of a word if it is a vowel (which means we will ignore it no matter what), you just need to edit the takeOutVowel method a bit.
static String takeOutVowel (String s)
{
// split your string so we can examine each word separately
String[] words = s.split(" ");
String noVowels = "";
for (int i = 0; i < words.length; i++){
char firstChar = words[i].charAt(0);
String temp = words[i].substring(1, words[i].length()).replaceAll("[aeiou]", "");
noVowels += firstChar + temp + " ";
}
return noVowels;
}
This works for your following requirement - Remove all vowels except for when the word starts with a vowel.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter some text, then hit enter: ");
String text = in.nextLine();
takeOutVowel(text);
System.out.println();
}
static void takeOutVowel(String s) {
String[] array = s.split(" "); // Split sentence into words and store them in an array.
StringBuilder finalString = new StringBuilder();
for (String word : array) { //For each word in the array
char ch = word.toLowerCase().charAt(0); //check if the lower case first character is a vowel.
if(ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u'){ // When it is not, replace all the vowels.
finalString = finalString.append(word.replaceAll("[aeiou]", "")).append(" ");
}else{
finalString = finalString.append(ch).append(word.replaceAll("[aeiou]", "")).append(" ");// When it is , replace all the vowels except the first character.
}
}
System.out.println(finalString);
}
}

How to count vowels and consonants and capitalizing first letter in a string while output using a method and return result

If a user enters a string: hello there
it should output
Hello has 2 vowels
There has 3 consonants.
I know this is a fairly simple code but I am getting too many ideas and getting confused.
I need a to make sure I have 2 methods for numberofVowels and capitalizeWord and both returns a result
I am getting an error and I am still trying to figure out to capitalize after I got counting vowels work
import java.util.Scanner;
public class Hwk9
{
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
}
public static int numberVowels(String string1)
{
int count = 0;
int vowels = 0;
int consonants = 0;
for (int i = 0; i < string1.length(); i++)
{
char ch = string1.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
}
Here is a simpler way of doing this, hope this helps:
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()));
}
Made something like this hope this helps, this will give vowels,consonants of each word
public static void main (String args[])
{
Scanner stdin = new Scanner(System.in);
String string1;
System.out.println("Enter a string");
string1 = stdin.nextLine();
string1 = string1.toLowerCase();
int count = 0;
int vowels = 0;
int consonants = 0;
for (String retval: string1.split(" ")){
for (int i = 0; i < retval.length(); i++)
{
char ch = retval.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
System.out.println(retval.substring(0, 1).toUpperCase() + retval.substring(1)+" has "+vowels+" vowels and "+consonants+" cosonants");
vowels=0;
consonants=0;
}
}
My code without scanner and maybe not very simple, but:
public class Main{
public static void main(String[] args) {
String test = "qwertyYVTA";
test = test.trim();
int vowels = 0;
int consonants = 0;
Pattern patternVow = Pattern.compile("[eyuioa]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherVow = patternVow.matcher(test);
while (matcherVow.find()) {
vowels++;
}
Pattern patternCons = Pattern.compile("[wrtpsdfghjklzxcvbnm]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher matcherCons = patternCons.matcher(test);
while (matcherCons.find()) {
consonants++;
}
System.out.println("Vowels in test String is " + vowels);
System.out.println("Consonants in test String is " + consonants);
}
}
following code will give you vowel and Constonent count
static String VOWEL_GROUP = "AEIOUaeiou";
static String testString = "AAAASHMAIOUAXCCDIOUGGGGA"; // say this is your text
public static void main(String[] args) {
int vovelCount = 0;
int consonantCount = 0;
for (int j = testString.length() - 1; j >= 0; j--) {//outer loop
for (int i = 0; i < VOWEL_GROUP.length(); i++) { //inner loop
if (VOWEL_GROUP.charAt(i) == testString.charAt(j)) {
vovelCount++; //vowel count in text
break;
}else{
consonantCount ++;
}
}
}
System.out.println(vovelCount+" "+ consonantCount);
}
I suggest you;
to create a final vowels array,
define a bool isVowel(char c) function and use it in your if condition.
Here is the simple code for counting the number of vowels using recursion
public static int vowels(String s){
int count =0;
char c;
if(s.length()==0){
return 0;
}
else{
c =s.charAt(0);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
count++;
}
return count+vowels(s.substring(1));
}
}
This looks way simple than above answers. It gets the input, converts it to lowercase then to an array of characters. A simple for loop will do the trick onwards.
import java.util.*;
public class FindVowelsConsonents {
public static void main(String[] args) {
int vowels_count = 0;
int consonents_count = 0;
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++){
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' ||
chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else
consonents_count++;
}
System.out.println(vowels_count+ " "+consonents_count);
sc.close();
}
}
As far as I am concerned you can use StringTokenizer:
String text = "dupalo twoja mama";
StringTokenizer tokenizer = new StringTokenizer(text,"aeiuo",false);
int vowels = tokenizer.countTokens();
System.out.println(vowels);
In this case of "text" it will print out 7.
import java.util.Scanner;
//don't use space in between the input string;
class StrRev {
static String Vowels ="aeiouAEIOU";
public static void main(String[] args){
#SuppressWarnings("resource")
Scanner name = new Scanner(System.in);
String nm = name.nextLine();
System.out.println();
int vowel=0;
int consonant=0;
for(int i=0;i<nm.length();i++){
for(int j=0;j<Vowels.length();j++){
if(Vowels.charAt(j)==nm.charAt(i)){
vowel++;
break;
}
}
}
consonant = nm.length()-vowel;
System.out.println("no of Vowels :"+vowel+"\nno of consonant :"+consonant);
}
}

Categories

Resources