Error counting vowels and consonant progr [duplicate] - java

At the end of my loop, I am planning on displaying the number of consonants and vowels in the sentence. I was wondering if there was a more efficient way to check how many consonants and vowels are in a given sentence, rather than using an if statement and manually inputting every letter. (key refers to my Scanner which has already been initialized)
Edit: It needs to ignore digits and other special characters, so for example if I write Hello# how 1are you?. There should be 8 vowels and 6 consonants.
System.out.println("Please enter the sentence to analyze: ");
String words = key.nextLine(); //the sentence the user inputs
int c = 0; //# of consonants
int v = 0; //# of vowels
int length = words.length(); //length of sentence
int check; //goes over each letter in our sentence
for(check = 0; check < length; check++){
char a = words.charAt(check);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
else if(a == 'b' || a == 'B' || a == 'c' || a == 'C' || a == 'd' || a == 'D' || a == 'f'
|| a == 'F' || a == 'g' || a == 'G' || a == 'h' || a == 'H' || a == 'j' || a == 'J'
|| a == 'k' || a == 'K' || a == 'l' || a == 'L' || a == 'm' || a == 'M' || a == 'n'
|| a == 'N' || a == 'p' || a == 'P' || a == 'q' || a == 'Q' || a == 'r' || a == 'r'
|| a == 's' || a == 'S' || a == 't' || a == 'T' || a == 'v' || a == 'V' || a == 'w'
|| a == 'W' || a == 'x' || a == 'X' || a == 'z' || a == 'Z')
c = c + 1;
}

Use Character.isLetter(ch) to determine if the character is a vowel or a consonant, then check to see if the character in question is in the set of vowels.
One way to create the set of vowels:
Set<Character> vowels = new HashSet<Character>();
for (char ch : "aeiou".toCharArray()) {
vowels.add(ch);
}
And to increment v or c:
if (Character.isLetter(a)) {
if (vowels.contains(Character.toLowerCase(a))) {
v++;
} else {
c++;
}
}

Assuming you already have a letter (vowel or consonant, not a digit nor a symbol or anything else), then you can easily create a method to define if the letter is a vowel:
static final char[] vowels = { 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y' };
public static boolean isVowel(char c) {
for (char vowel : vowels) {
if (c == vowel) {
return true;
}
}
return false;
}
public static boolean isConsonant(char c) {
return !isVowel(c);
}
Note that I set Y and y as vowels since seems that they are in your language. In Spanish and English, Y is a consonant (AFAIK).
You can easily check if the char is a letter or not using Character#isLetter.
So, your code would become into:
for(check = 0; check < length; check++){
char a = words.charAt(check);
if (Character.isLetter(a)) {
if (isVowel(a)) {
v++;
} else {
c++;
}
}
}

How about something like
String vowels = "aeiouyAEIOUY"; // you can declare it somewhere before loop to
// to avoid redeclaring it each time in loop
//inside loop
if ((a>='a' && a<='z') || (a>='A' && a<='Z')){ //is letter
if (vowels.indexOf(a)!=-1) //is vowel
v++;
else //is consonant
c++;
}

I am sure this can be improved upon, but I'll throw it in the ring anyways.
Remove non-characters from the sentence, lowercase it, then convert to a char array and compare it to a char array of vowels that are all lowercase.
String myText = "This is a sentence.";
int v = 0;
char[] vowels = {'a','e','i','o','u'};
char[] sentence = myText.replaceAll("[^a-zA-Z]","").toLowerCase().toCharArray();
for (char letter : sentence) {
for (char vowel : vowels) {
if (letter == vowel) {
v++;
}
}
}
System.out.println("Vowels:"+ v);
System.out.println("Consonants:" + (sentence.length -v));

One easy way would be to create 2 lists:
one contains vowels (a, e, i, o, u)
the other contains consonants
Then you iterate over each character in the Java string.
See a sample below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Counter {
public static void main(String[] args) {
String test = "the fox is in the woods";
test = test.toLowerCase();
List<Character> vowels = new ArrayList<Character>();
vowels.addAll(Arrays.asList(new Character[]{'a', 'e', 'i', 'o', 'u'}));
List<Character> consonants = new ArrayList<Character>();
consonants.addAll(Arrays.asList(new Character[]{'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'}));
int vcount = 0;
int ccount = 0;
for (int i = 0; i < test.length(); i++){
Character letter = test.charAt(i);
if (vowels.contains(letter)){
vcount ++;
} else if (consonants.contains(letter)){
ccount++;
}
}
System.out.println(vcount);
System.out.println(ccount);
}
}

You can do a range check to make sure it is a letter, then check if it one of the vowels:
if( ( a >= 'a' && a<= 'z' ) || ( a >= 'A' && a <= 'Z' ) )
{
// is letter
switch( a )
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'U': case 'u':
++v;
break;
default: // don't list the rest of the characters since we did the check in the if statement above.
++c;
}
}

Oh, there's certainly a much more readable way to do it. Not sure if that meets the "better" definition.
As a start, I'd suggest that you encapsulate what you have into methods that you can write once and call anywhere:
package misc;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ParseUtils get counts of vowels and consonants in sentence
* #author Michael
* #link https://stackoverflow.com/questions/24048907/how-can-i-check-how-many-consonants-and-vowels-there-are-in-a-sentence-in-java
* #since 6/4/2014 6:57 PM
*/
public class ParseUtils {
private static final String VOWEL_PATTERN_STR = "(?i)[aeiou]";
private static final Pattern VOWEL_PATTERN = Pattern.compile(VOWEL_PATTERN_STR);
private static final String CONSONANT_PATTERN_STR = "(?i)[b-df-hj-np-tv-z]";
private static final Pattern CONSONANT_PATTERN = Pattern.compile(CONSONANT_PATTERN_STR);
private ParseUtils() {}
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("sentence: '%s' # letters: %d # vowels: %d # consonants %d", arg, arg.length(), getNumVowels(arg), getNumConsonants(arg)));
}
}
public static int getNumVowels(String sentence) {
return getMatchCount(sentence, VOWEL_PATTERN);
}
public static int getNumConsonants(String sentence) {
return getMatchCount(sentence, CONSONANT_PATTERN);
}
private static int getMatchCount(String s, Pattern p) {
int numMatches = 0;
if ((p != null) && (s != null) && (s.trim().length() > 0)) {
Matcher m = p.matcher(s);
while (m.find()) {
++numMatches;
}
}
return numMatches;
}
}

Split the String by whitespaces and and Calculate only the number of Vowels. Then Number of consonants = Length of Sentence - No. of Vowels.
Detailed Code:
System.out.println("Please enter the sentence to analyze: ");
int v = 0;
int c = 0;
String string = key.nextLine(); //the sentence the user inputs
String[] stringArray = string.split(" ");
for(int i=0;i<stringArray.length;i++)
{
for(int j= 0; j<string.length(); j++)
{
char a = string.charAt(j);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
}
c= c+(stringArray.length)-v;
}
System.out.println("Vowels:"+v+" and Consonants:"+c);

One way to do it is to get rid of the non-letters, then vowels and consonants, and get the length of what is left:
public class CountChars {
public static final String CONSONANTS = "[BCDFGHJKLMNPQRSTVWXYZ]";
public static final String VOWELS = "[AEIOU]"; // considering Y a consonant here
public static final String NOT_LETTERS = "[\\W_0-9]";
public static void main(String[] args) {
String words = "How can I check how many consonants and vowels there are in a sentence in Java?";
String letters = words.toUpperCase().replaceAll(NOT_LETTERS, "");
System.out.println("Letters: " + letters.length());
String vowels = letters.replaceAll(CONSONANTS, "");
System.out.println("Vowels: " + vowels.length());
String consonants = letters.replaceAll(VOWELS, "");
System.out.println("Consonants: " + consonants.length());
}
}

Here is the best way of doing this:
public static void checkVowelsAndConsonants(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()));
}

Related

How can I search for a character in strings without using a loop?

My assignment is: if the user-inputted word has no vowels, then "ay" is added to the end, if it starts with a vowel then it adds "yay" to the end, otherwise if it doesn't meet any of these conditions then the first letter gets moved to the end of the word and "ay" is added to the end. I can't seem to get the last condition to work. For example the word "sad" should output "adsay" but instead it outputs "saday" which means that it is reading and accepting another if statement. I've tried to look up some solutions but all I've gotten are loops and I'd like to avoid loops for this particular assignment. Here is my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Word: ");
String word = in.nextLine();
int length = word.length();
String word1 = "";
if (word.charAt(0) == 'a' || word.charAt(0) == 'e' || word.charAt(0) == 'i' || word.charAt(0) == 'o' || word.charAt(0) == 'u')
{
word1 = pigLatin(word);
System.out.println("Pig Latin: " + word1);
}
else if (word.indexOf("a") == -1 || word.indexOf("e") == -1 || word.indexOf("i") == -1 || word.indexOf("o") == -1 || word.indexOf("u") == -1)
{
word1 = pigLatin1(word);
System.out.println("Pig Latin: " + word1);
}
else
{
word1 = pigLatin2(word);
System.out.println("Pig Latin: " + word1);
}
}
static String pigLatin(String word)
{
String x = word + "yay";
return x;
}
static String pigLatin1(String word)
{
String x = word + "ay";
return x;
}
static String pigLatin2(String word)
{
char firstLetter = word.charAt(0);
String x = word.substring(1, word.length()) + firstLetter + "ay";
return x;
}
}
The problem lies in your second if statement:
else if (word.indexOf("a") == -1 || word.indexOf("e") == -1 || word.indexOf("i") == -1 || word.indexOf("o") == -1 || word.indexOf("u") == -1)
{
word1 = pigLatin1(word);
System.out.println("Pig Latin: " + word1);
}
Because you're using "or" here (the || operator), your program will enter this block as long as the word doesn't contain "a", or doesn't contain "e", etc. For your test input, "sad" contains "a" but it doesn't contain "e"... so you wind up calling pigLatin1("sad").
Change this if to use "and" instead (the && operator). That way, the word will need to not have every defined vowel, instead of not having at least one defined vowel.
else if (word.indexOf("a") == -1 && word.indexOf("e") == -1 && word.indexOf("i") == -1 && word.indexOf("o") == -1 && word.indexOf("u") == -1)

Why does the do/while loop keep adding the input each time the switch statement fires?

Write a class with a constructor that accepts a String object as its argument. The class should have a method that
returns the number of vowels in the string, and another method that returns the number of consonants in the string.
Demonstrate the class in a program that performs the following steps:
The user is asked to enter a string.
The program displays the following menu:
a: Count the number of vowels in the string
b: Count the number of consonants in the string
c: Count both the vowels and consonants in the string
d: Enter another string
e: Exit the program.
The program performs the operation selected by the user and repeats until the user selects e, to exit the program.
When the user enters a string and checks for consonants, or vowels, or both once, it works just fine.
But when it is passed again, the program doubles the value.
Thoughts?
Class:
public class CounterClass
{
String string;
int vow = 0;
int con = 0;
char letter = ' ';
int enter = 0;
/**
* This is a Constructor
* It accepts a string object.
*/
public CounterClass(String aString)
{
this.string = aString;
}
/* #returns an int
* This method checks for char and then adds it to a vowel counter */
public int getVowels(String aString)
{
int length = aString.length();
for( int i = 0; i < length ; i++)
{
char c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i'|| c == 'o'
|| c == 'u' ||c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U')
{
vow++;
}
}
return vow;
}
/* #returns an int
* This method checks for char and then adds it to a con counter */
public int getConsonants(String aString)
{
int length = aString.length();
for( int i = 0; i < length ; i++)
{
char c = aString.charAt(i);
if (c == 'B' || c == 'C' || c == 'D'|| c == 'F'
|| c == 'G' ||c == 'H' || c == 'J' || c == 'K'
|| c == 'L' || c == 'M'|| c == 'N' || c == 'P'|| c == 'Q'
|| c == 'R' ||c == 'S' || c == 'T' || c == 'V'
|| c == 'W' || c == 'X'|| c == 'Z' || c == 'b' || c == 'c' || c == 'd'|| c == 'f'
|| c == 'g' ||c == 'h' || c == 'j' || c == 'k'
|| c == 'l' || c == 'm'|| c == 'n' || c == 'p'|| c == 'q'
|| c == 'r' ||c == 's' || c == 't' || c == 'v'
|| c == 'w' || c == 'x'|| c == 'z')
{
con++;
}
}
return con;
}
}
Main Program :
import javax.swing.JOptionPane;
public class NumberCounters
{
public static void main(String [] args)
{
//Declaring variable for later use.
String input = " ";
String letters = " ";
char letter = ' ';
StringBuilder sb = new StringBuilder();
//This creates an instance of CounterClass
CounterClass string = new CounterClass(input);
//Tests
System.out.println(string.getVowels(input));
System.out.println(string.getConsonants(input));
input = JOptionPane.showInputDialog("Please enter a string"); // Getting a string input from the user.
//Does a loop until the user selects 'e'
do{
//sets 'letters' to the inputdialog from the menu
letters = JOptionPane.showInputDialog(
"a: Count the number of vowels in the string\n" +
"b: Count the number of consonants in the string\n" +
"c: Count both the vowels and consonants in the string\n"+
"d: Enter another string\n" + "e: Exit the program");
letter = letters.charAt(0); // letters is a string so I used charAt to grab the first letter from the input.
switch(letter)
{
case 'A':
case 'a': JOptionPane.showMessageDialog(null, "You have " + string.getVowels(input) + " vowels in your string");
break;
case 'B':
case 'b': JOptionPane.showMessageDialog(null, "You have " + string.getConsonants(input) +
" consonants in your string");
break;
case 'C':
case 'c': JOptionPane.showInputDialog(null, "You have " + string.getConsonants(input)
+ " Consonants and " + string.getVowels(input)
+ " vowels in your string");
break;
case 'D':
case 'd': input = JOptionPane.showInputDialog("Please enter a string");
break;
case 'E':
case 'e':
System.exit(0);
}
}while( letter != 'e');
}
}
try setting your values back to 0 in each method you could also remove the getConsonants method and just place an else(example of edited code below)
public int getVowels(String aString)
{
//set values to back to 0 before checking
vow = 0;
con = 0;
int length = aString.length();
for( int i = 0; i < length ; i++)
{
char c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i'|| c == 'o'
|| c == 'u' ||c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U')
{
vow++;
}
else if(c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9' || c == '0' ||){
//in case you add numbers put here
}
else
{
con++;
}
}
return vow;

SyllableCounter counts the Syllables in a word

I am trying to work on a syllable counter that counts the syllables in the string I enter. Here are the instructions. -
Syllables are really useful for a lot of things. They are defined according to the following rules involving
consonants (non-vowels) and vowels (a, e, i, o, u, y):
Starting y omitted:
(a) when words begin with y, we don’t count the starting y as a vowel. (we are
assuming there are no words that start with y followed immediately by a consonant)
Silent e omitted:
(a) when e is the last letter of a word, we’ll assume it is silent, unless the word is café or
entrée (words borrowed from French). (* we’ll ignore all other words to simplify)
For simplification, it may be best to create a new String without this silent e, before
checking for more syllables.
With the silent-e omitted, one-syllable units:
(a) have a single vowel.
(b) have two vowels that are the same letter in succession.
(c) have two vowels in immediate succession that are ei, ie, ea, ou, ey, ay, oy, uy, ai.
(d) have three vowels in immediate succession that are eau, iou (* yes, there are
exceptions to this that we are ignoring here).
With the silent-e omitted, two-syllable units:
(a) two vowels in immediate succession where the vowels are different letters not
following the rule above. For instance, oe, io, oi.
(b) three vowels in immediate succession not following the rule above where the last
vowel is not a silent e. For instance (“eye”) as in “meyer.”
Generate a program called SyllableCounter that counts syllables in a word or sentence (maximum one
line). Assume the user will not use any punctuation. Pseudocode and a testing plan are required.
Do not print in main().
Sample output:
Please enter your word or sentence, followed by a carriage return.
Sally where are you going
Your entry has 7 syllables.
Here is my current code (It compiles, but has a StringIndexOutOfBoundsException -
/*
* SyllableCounter.java
* Prints the number of syllables based on an inputed string
*
* Testing - What should work - All strings with letter characters
* What shouldn't work - Number values
*/
import java.util.Scanner; //import the scanner
public class SyllableCounter //class is SyllableCounter
{
public static void main (String args[]) //main() method header
{
String string = "";
string = getInput(); //call getInput()
int totalCount = calc(string); //call calc()
printOut(totalCount); //call printOut()
}
public static String getInput() //getInput() method
{
Scanner console = new Scanner (System.in); //create an instance of the scanner
System.out.println("Please enter your word or sentence, followed by a carrige return");
String input = console.nextLine(); //get the inputted string and return it
return input;
}
public static int calc (String string)
{
//int finalCount = 0;
//int index = string.indexOf(' ');
return calcWord(string);
}
public static int calcWord(String word) //calc() method
{
int count = 0;
//for loop goes through all charectors
int length = word.length();
for (int i = 0; i<length; i++)
{
if ((word == "entree") || (word == "cafe"))
return 2;
else if (i==0)//if i is 0
{
if (word.charAt(i) == 'a' //if letter is a,e,i,o or u
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u')
count++ ; //count ++
else //else
{} //nothing
}
else if (i==word.length()-1) //else if i is the last letter of the string
{
if ( (word.charAt(i) == 'a') || (word.charAt(i) == 'i') || (word.charAt(i) == 'o') || (word.charAt(i) == 'u') || (word.charAt(i) == 'y') )
//else if letter is a,i,o,u or y (also 2 or 3 in a row)
{
count ++ ;//count ++
}
else //else
{} //nothing
}
else if (word.charAt(word.length()-1) == 'e') {
if (length >= i+2)
if ( word.substring(i,i+3) == "eau"
|| word.substring(i,i+3) == "iou" )
{
count++;
i+=2;
}
else if ( word.substring(i,i+2) == "ei"
|| word.substring(i,i+2) == "ie"
|| word.substring(i,i+2) == "ea"
|| word.substring(i,i+2) == "ou"
|| word.substring(i,i+2) == "ey"
|| word.substring(i,i+2) == "ay"
|| word.substring(i,i+2) == "oy"
|| word.substring(i,i+2) == "uy"
|| word.substring(i,i+2) == "ai" )
{
count++;
i++;
}
else if( word.substring(i, i+2) == "oe"
|| word.substring(i, i+2) == "io"
|| word.substring(i, i+2) == "oi" )
{
count+=2;
i++;
}
}
else {
if (word.charAt(i) =='a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
}
if (!(word.charAt(word.length()-1) == 'e'))
{
if ( word.substring(i,i+3) == "eau")
{
count++;
i+=2;
}
else if (word.charAt(i) == 'a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
}
else if (word.charAt(i) == 'a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
else //else
{} //nothing
}
return count;//return the count
}
public static void printOut(int count) //printOut() method
{
System.out.println(count);
// print the count
}
}
I used the word "foo" as input to your program:
Here (around line 112 for me) :
if (!(word.charAt(word.length()-1) == 'e')){
if ( word.substring(i,i+3) == "eau")
An example of how the above section of code fails is using the word foo:
The char at word length-1 is not e so therefore this condition above will be evaluated. However, when i is equal to 1 i+3 will equal 4. So, 4 is outside the length of "foo" causing the error.
Keep in mind this is just one example of this type of failure. Make sure that whenever you are getting a substring from i to i+n the string being evaluated has i+n chars left.
Manually finding the solution is a lot of work. Regular Expression could be a sweet solution to your problem. Have a look at the link below:
How to calculate syllables in text with regex and Java
Also be reminded that the above reference doesnot consider Y as a syllable, you will have to tweak the regular expression a bit to get the desired output. Plus the vowel "e" needs some checking to be done to get the exact results.

PigLatin program help...Capitalize?

I have the program working except for the capitalization part:
Here's how to translate the English word englishWord into the Pig Latin word pigLatinWord:
a. If there are no vowels in englishWord, then pigLatinWord is just englishWord + "ay". (There are ten vowels: 'a', 'e', 'i', 'o', and 'u', and their uppercase counterparts.)
b. Else, if englishWord begins with a vowel, then pigLatinWord is just englishWord + "yay".
c. Otherwise (if englishWord has a vowel in it and yet doesn't start with a vowel), then pigLatinWord is end + start + "ay", where end and start are defined as follows:
1. Let start be all of englishWord up to (but not including) its first vowel.
2. Let end be all of englishWord from its first vowel on.
3. But, if englishWord is capitalized, then capitalize end and "uncapitalize" start.
How do you do the capitalization part?
So far, I get Hasta= astaHay. It should be Hasta = Astahay
Here is the basic program so far:
public static boolean isVowel(char c) {
if (c == 'a' && c == 'A') {
return true;
} else if (c == 'e' && c == 'E') {
return true;
} else if (c == 'i' || c == 'I') {
return true;
} else if (c == 'o' || c == 'O') {
return true;
} else if (c == 'u' || c == 'U') {
return true;
} else {
return false;
}
}
public static String convertPigLatinWord(String englishWord) {
int length = englishWord.length();
if (englishWord.charAt(length - 1) == '.' && englishWord.charAt(length - 1) == '!' && englishWord.charAt(length - 1) == '?') {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1, length - 1);
return (rest + ch + "ay" + englishWord.charAt(length - 1) + "\"" + " ");
} else if (isVowel(englishWord.charAt(0))) {
return (englishWord + "yay" + " ");
} else {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1);
return (rest + ch + "ay" + " ");
}
}
public String translate() {
String pigLatinPhrase = "";
while (englishPhrase.length() > 1) {
String word = getWord();
pigLatinPhrase += convertPigLatinWord(word) + " ";
}
return pigLatinPhrase;
}
public static void main(String[] args) {
String answer = "";
do {
Scanner keyboard = new Scanner(System.in);
String input;
System.out.print("Please enter an English phrase: ");
input = keyboard.nextLine();
PigLatin3 first = new PigLatin3(input);
System.out.println(first.translate());
System.out.println("Would you like to translate another phrase? (y or n)");
answer = keyboard.nextLine();
} while (!(answer.equals("N")) && !(answer.equals("n")));
System.exit(0);
}
}
You can capitalize a letter by breaking the string to substrings and then capitalizing them:
String word = word.substring(0, 1).toUpperCase() + word.substring(1);
So just use the toUpperCase() and toLowerCase() methods of String ...
There is also a neat trick that you can use with single characters based on the ASCII table. Just xor them with 32 to get the other case.
What you are looking for is something like this:
public static String onlyFirstLetterUpperCase(String a){
int i;
for (i = 0; i < a.length(); i++){
if("AEIOUaeiou".indexOf(a.charAt(i)) != -1 )
break;
// indexOf looks for a char in a given string and returns its
// position or -1 if not found. So if this indexOf returns -1 I can be sure,
// that the character is not a vowel
}
return a.substring(0, i + 1).toUpperCase() + a.substring(i + 1).toLowerCase();
}
Just call this method after performing your operations

Taking vowels from string. Java

I'm having trouble with this simple exercise. What I have to do is to take the vowels from the string.
This returns all the vowels in the string, but what I want is that if there are multiple letters of same vowel, just return one.For example, using the string "aaa eee iii" should give "a e i".
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u')) {
aChar = aString.charAt(i);
System.out.print(aChar + " ");
}
}
}
I would recommend either adding each vowel found to a HashSet<Character>, or calling aString.contains() with each vowel in turn. You can also use aString.toLowerCase() so that you only have to check for lowercase vowels.
Edit your code as follows:
public static void getVowels(char aChar, String aString)
{
System.out.print("Your string has the following vowels: ");
String vowels="";
for (int i = 0; i < aString.length(); i++)
{
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u'))
{
if(!vowels.contains(String.valueOf(aString.charAt(i))))
vowels+=aString.charAt(i);
}
}
for(int i=0;i<vowels.length();i++)
System.out.print(vowels.charAt(i)+" ");
}
EDIT :
Alternatively,
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
char vowels[]={'a','e','e','o','u'};
for (char vowel : vowels)
{
if(aString.indexOf(vowel)>=0)
{
System.out.print(vowel+" ");
}
}
}
Why are you doing for loop? Just check String.IndexOf() and if that character is present print it.
You need to have a string where you keep on adding unique vowels checking before hand whether it exists. The below program will clear your doubt.
public class TestWovel {
public static void main(String[] args) {
String vowel = "aaaeeeiiizncnzcxjswdmmnmxcuuooo";
String uniqueVowels = "";
for(int i=0;i<vowel.length();i++){
char vowelFound = vowel.charAt(i);
if((vowelFound == 'a' || vowelFound == 'e' || vowelFound == 'i' || vowelFound == 'o' || vowelFound == 'u') && (uniqueVowels.indexOf(vowelFound) == -1)){
uniqueVowels+=vowelFound;
}
}
System.out.println(uniqueVowels);
}
}
You could use an integer array whose indexes are ASCII codes. When you see a vowel, check its count in the array. If the count is 0, print the vowel and increase the count. For example, 'a' would be stored in arr[97]:
public static void getVowels(String aString) {
int[] arr = new int[128];
char c;
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
if (arr[c] == 0) {
System.out.print(aString.charAt(i) + " ");
arr[c]++;
}
}
}
}

Categories