Java phrase guessing game - java

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.

Related

How to get correct output for Pig Latin translator using JAVA

I am coding a JAVA application that translates english to pig latin. My application runs with no actual errors but the output is automatic and incorrect. This application will continue to run if the user selects "y".
Can you all see where my error lies?
Thank you.
CODE:
import java.util.Scanner;
public class PigLatin2 {
public static void main(String[] args) {
// create a Scanner object
Scanner sc = new Scanner(System.in);
// Run through the loop of calculations while user choice is equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("Enter a line to be translated");
System.out.println();
//Get String entered
String userInput = sc.toString();
//Line break
System.out.println();
String[] words = userInput.split(" ");
String output = "";
for(int i = 0; i < words.length; i++) {
String pigLatin = translated(words[i]);
output += pigLatin + " ";
}
System.out.println(output);
//Scan next line
sc.nextLine();
//line break
System.out.println();
// Ask use they want to continue
System.out.print("Continue? (y/n): ");
//Users choice
choice = sc.nextLine();
System.out.println();
}//END WHILE LOOP
//Close scanner object
sc.close();
}//END MAIN METHOD
private static String translated(String words) {
String lowerCase = words.toLowerCase();
int firstVowel = -1;
char ch;
// This for loop finds the index of the first vowel in the word
for (int i = 0; i < lowerCase.length(); i++) {
ch = lowerCase.charAt(i);
if (startsWithVowel(ch)) {
firstVowel = i;
break;
}
}
if (firstVowel == 0) {
return lowerCase + "way";
}else {
String one = lowerCase.substring(firstVowel);
String two = lowerCase.substring(0, firstVowel);
return one + two + "ay";
}
}
public static Boolean startsWithVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
}
This is the output I get automatically:
ava.util.scanner[delimiters=\p{javawhitespace}+][position=0][matchjay alid=false][needvay input=false][sourceway osed=false][skipped=false][groupclay eparator=\,][decimalsay eparator=.][positivesay efix=][negativepray efix=\q-\e][positivepray uffix=][negativesay uffix=][nansay ing=\qnan\e][infinitystray ing=\q?\e]stray

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);
}
}

Counting vowels in a string and wrong output?

I am very new to java and I was wondering if you could help me out. Here is my code:
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
for (int i = 0; i <= length; i++) {
String letter = string.substring(i, ++i);
if (letter.equalsIgnoreCase("a")){vowels++;}
if (letter.equalsIgnoreCase("e")){vowels++;}
if (letter.equalsIgnoreCase("i")){vowels++;}
if (letter.equalsIgnoreCase("o")){vowels++;}
if (letter.equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}
The number is off but I can't figure out why.
This here is wrong
string.substring(i, ++i)
because the variable i is already incremented in the for-loop
so you are basically skipping chars in the string
implement the right logic, use the right data type
int length = string.length();
for (int i = 0; i < length; i++) {
char letter = string.charAt(i);
System.out.println(letter);
if (letter == 'a') {
vowels++;
} else if (letter == 'e') {
vowels++;
} else if (letter == 'i') {
vowels++;
} else if (letter == 'o') {
vowels++;
} else if (letter == 'u') {
vowels++;
}
}
Here is another solution you could try:
The split method will split the string into a String array. Then in your for loop it will check every item in your array.
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
String[] stringArray = string.split("");
for (int i = 0; i < length; i++) { //I took out the = sign in your for loop arguments.
if (stringArray[i].equalsIgnoreCase("a")){vowels++;}
if (stringArray[i].equalsIgnoreCase("e")){vowels++;}
if (stringArray[i].equalsIgnoreCase("i")){vowels++;}
if (stringArray[i].equalsIgnoreCase("o")){vowels++;}
if (stringArray[i].equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}

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