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()));
}
import java.util.Scanner;
public class Ariete25Programs {
public static void main(String[] tin) {
char again = 0;
int choose;
if(choose == 7) {
char again7 = 0;
do
{
System.out.println("---Vowels and Consonants---");
String line;
System.out.println("Enter word: ");
line = sc.nextLine();
String vowels = " ", consonants = " ", digits = " ", spaces = " ";
for(int i = 0; i < line.length(); ++i)
{
char ch = line.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I'
|| ch == 'O' || ch == 'U')
{
vowels+=line.charAt(i);
}
else if((ch >= 'a'&& ch <= 'z'))
{
consonants+=line.charAt(i);
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Try Again? (Y/N)");
again7 = sc.next().charAt(0);
if(again7 == 'n') {
System.out.println("Menu? [y/n]");
again = sc.next().charAt(0);
}
else if(again7 == 'n') {
System.out.println("Thank you for using the programs!");
System.exit(0);
}
}
while(again7 == 'y');
then the result when you choose 7 becomes like this
-----Vowels and Consonants-----
Enter word:
Try again?(Y/N)
can someone help me? I can't seem to figure out the problem in my codes. It keeps on skipping.
I guess you do something like choose = sc.nextInt(); you should try choose = Integer.parseInt(sc.nextLine());
Please replace sc.next().charAt(0) with sc.nextLine().charAt(0).
Documentation:
Scanner.next()
Scanner.nextLine()
Moreover else if(again7 == 'n') is wrong since you already did the same check few lines before, so you'll never execute the code in that else if block
do
{
System.out.println("---Vowels and Consonants---");
String line;
System.out.println("Enter word: ");
line = sc.nextLine();
String vowels = " ", consonants = " ", digits = " ", spaces = " "; // digits and spaces are not used
int end = line.length();
for (int i = 0; i < end; ++i) {
char ch = line.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I'
|| ch == 'O' || ch == 'U') {
vowels += line.charAt(i);
}
else if ((ch >= 'a'&& ch <= 'z')) {
consonants += line.charAt(i);
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Try Again? (Y/N)");
again7 = sc.nextLine().charAt(0);
if (again7 == 'n') {
System.out.println("Menu? [y/n]");
again = sc.nextLine().charAt(0);
if (again == 'n') {
System.out.println("Thank you for using the programs!");
break;
} else {
// display Menu
}
}
} while(again7 == 'y');
I'm new to Java and programming in general. This is baffling me, and I feel like I may just need to scrap what I have and go a different route, but I don't know what route to take.
Below is the code I've written for translating a line from the user into braille. It works! Unfortunately, it works vertically. How can I, after using three lines to create the braille, make the next braille character appear next to the previous one instead of below it?
import java.util.*;
public class Program4
{
public static String code1 = ". |";
public static String code2 = " .|";
public static String code3 = "..|";
public static String code4 = " |";
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Program 4 by Ross Walker");
System.out.println();
String s;
System.out.println("Please give a line to translate");
s = keyboard.nextLine();
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == '1' || c == 'a')
{
//new Program4().letterA(s.charAt(i));
System.out.printf("%s%n%s%n%s%n", code1, code4, code4);
System.out.println();
}
if((c == '2' ) || (c == 'b'))
{
System.out.printf("%s%n%s%n%s%n", code1, code1, code4);
System.out.println();
}
if((c == '3') || (c == 'c'))
{
System.out.println(code3);
System.out.println(code4);
System.out.println(code4);
System.out.println();
}
if((c == '4') || (c == 'd'))
{
System.out.println(code3);
System.out.println(code2);
System.out.println(code4);
System.out.println();
}
if((c == '5') || (c == 'e'))
{
System.out.println(code1);
System.out.println(code2);
System.out.println(code4);
System.out.println();
}
if((c == '6') || (c == 'f'))
{
System.out.println(code3);
System.out.println(code1);
System.out.println(code4);
System.out.println();
}
if((c == '7') || (c == 'g'))
{
System.out.println(code3);
System.out.println(code3);
System.out.println(code4);
System.out.println();
}
if((c == '8') || (c == 'h'))
{
System.out.println(code1);
System.out.println(code3);
System.out.println(code4);
System.out.println();
}
if((c == '9') || (c == 'i'))
{
System.out.println(code2);
System.out.println(code1);
System.out.println(code4);
System.out.println();
}
if((c == '0') || (c == 'j'))
{
System.out.println(code2);
System.out.println(code3);
System.out.println(code4);
System.out.println();
}
}
}
}
I've only written up to j in the alphabet. I'll continue if this is the only way I can get it done, but I'd like your help to do it the right way if possible.
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int countVowel=0;
int countVowelA=0;
int countVowelE=0;
int countVowelI=0;
int countVowelO=0;
int countVowelU=0;
char ch;
String str;
System.out.println("Please enter the string : ");
str = sc.nextLine();
for(int i = 0; i<=str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch =='A')
{
countVowelA++;
countVowel++;
}
if(ch == 'e' || ch =='E')
{
countVowelE++;
countVowel++;
}
if(ch == 'i' || ch =='I')
{
countVowelI++;
countVowel++;
}
if(ch == 'o' || ch =='O')
{
countVowelO++;
countVowel++;
}
if(ch == 'u' || ch =='U')
{
countVowelU++;
countVowel++;
}
i++;
}
System.out.println("Occurances of A in given string : " +countVowelA);
System.out.println("Occurances of E in given string : " +countVowelE);
System.out.println("Occurances of I in given string : " +countVowelI);
System.out.println("Occurances of O in given string : " +countVowelO);
System.out.println("Occurances of U in given string : " +countVowelU);
System.out.println("Number of vowels in strings are : " +countVowel);
}
}
For me i am having trouble, let's say for example if i type lebron james is the best basketball player, u know it. It gives me an error and also it doesn't count all the vowels? Also, can u tell if my code is right
check line below
for(int i = 0; i<=str.length(); i ++)
change to
for(int i = 0; i<str.length(); i ++)
why?
Because in Java, index start from zero. When you have i <= str.length, it goes beyond scope index of string and gives you java.lang.StringIndexOutOfBoundsException
Another issue, You have incremented variable i twice. Second after if clauses is totally unnecessary because it gives you wrong answer even if you rectify the boundary issue.
Your loop variable i, as was mentioned in the comments, is incremented twice. Once in the for statement itself, and the other at the end of the loop.
This means that the counter goes: 0,2,4,6 instead of 0,1,2,3.
That will give you the wrong answer.
However, the reason for the error is not this, but the fact that you check the condition until i <= str.length(), instead of i < str.length(). The characters in a string with, say, 3 characters like "the" are 0,1,2. There is no character number 3. So when i is equal to str.length, you get an error.
Try this code
import java.util.Scanner;
public class CountVowels {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int countVowel=0;
int countVowelA=0;
int countVowelE=0;
int countVowelI=0;
int countVowelO=0;
int countVowelU=0;
char ch;
String str;
System.out.println("Please enter the string : ");
str = sc.nextLine();
char[] c = str.toCharArray();
for(int i = 0; i<c.length; i ++)
{
if(c[i] == 'a' || c[i] =='A')
{
countVowelA++;
countVowel++;
}
else if(c[i] == 'e' || c[i] =='E')
{
countVowelE++;
countVowel++;
}
else if(c[i] == 'i' || c[i] =='I')
{
countVowelI++;
countVowel++;
}
else if(c[i] == 'o' || c[i] =='O')
{
countVowelO++;
countVowel++;
}
else if(c[i] == 'u' || c[i] =='U')
{
countVowelU++;
countVowel++;
}
//i++;
}
System.out.println("Occurances of A in given string : " +countVowelA);
System.out.println("Occurances of E in given string : " +countVowelE);
System.out.println("Occurances of I in given string : " +countVowelI);
System.out.println("Occurances of O in given string : " +countVowelO);
System.out.println("Occurances of U in given string : " +countVowelU);
System.out.println("Number of vowels in strings are : " +countVowel);
}
}
Sort all words by comparing the number of vowels that each word contains. The
word with the fewest number of vowels would come first. If you have more than one word with the same number of vowels, that group would be sorted alphabetically.
I believe that I have most of the project completed, I just don't know why it's not working.
public class Word implements Comparable<Word> {
private String word;
public Word(String s) {
word = s;
}
private int numVowels() {
String vowels = "AEIOUaeiou";
int vowelCount = 0;
for (int i = 0; i < vowels.length(); i++) {
if ((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u')) {
return vowelCount;
}
}
return vowelCount;
}
public int compareTo(Word rhs) {
for (int i = 0; i < word.length(); i++) {
if ((word.charAt(i) == 'a') || (word.charAt(i) == 'A')) {
System.out.println(word);
} else if ((word.charAt(i + 1) == 'e') || (word.charAt(i + 1) == 'E')) {
System.out.println(word);
}
}
return -1;
}
public String toString() {
return word;
}
}
I think my error is in the compareTo method. I'm not sure. Would anyone be able to help me?
First - I didn't realize that Word was your custom class. That said...there's a lot of flaws with it.
Your compareTo method is really, effectively, only comparing two Strings together. What you want to do is something like this:
public int compareTo(Word other) {
return word.compareTo(other.getWord());
}
The reason for this is that String implements Comparable<String>.
Now, if this isn't what you're going for (and I'm really not sure what that exactly is), then you may look into comparing the number of vowels two Word instances have.
public int compareTo(Word other) {
return word.numVowels() - other.numVowels();
}
The above will return a positive value if the current Word has more vowels than the Word being compared to, a negative value if there are less, or zero if the vowels are equivalent.
Next, your numVowels() method is completely broken. Look at what you're iterating across: vowels. The vowels String is always a constant value. It's never going to change - there are exactly ten vowels, five lower case, and five upper case.
What you want to do is check your word field against the set of vowels.
Here's a better* solution: use a Set<Character> - you get constant look up time for them all.
Set<Character> vowelSet = new HashSet<Character>() {{
add('a');
add('A');
add('e');
add('E');
add('i');
add('I');
add('o');
add('O');
add('u');
add('U');
}};
Then, all you have to do in your loop is this:
int count = 0;
for(char c : word.toCharArray()) {
if(vowelSet.contains(c)) {
count++;
}
}
return count;
*It doesn't take into account that Y is sometimes a vowel.
if((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u') || (vowels.charAt(i) == 'A') || (vowels.charAt(i) == 'E') || (vowels.charAt(i) == 'I') || (vowels.charAt(i) == 'O') || (vowels.charAt(i) == 'U'))
{
vowelCount++;
}
You were previously returning 0 when you returned vowelCount. You need to increment vowelCount when you find vowels and then return it after you're done looping. You also need to check for upper case vowels and not just lower case vowels to get an accurate count.
Your compareTo method is not even close to correct...
First of all, try not to post your Homework on here. Your numVowels() method is wrong too.
private int numVowels() //FIXED METHOD
{
String vowels = "AEIOUaeiou";
int vowelCount = 0;
for(int i = 0; i < vowels.length(); i++)
{
if((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u') || (vowels.charAt(i) == 'A') || (vowels.charAt(i) == 'E') || (vowels.charAt(i) == 'I') || (vowels.charAt(i) == 'O') || (vowels.charAt(i) == 'U'))
{
return vowelCount; //Will return lowercase AND capital vowels :)
}
}
return vowelCount;
}
Your original code only searched for lowercase 'a', 'e', 'i', 'o', and 'u'. I added capitals to your if statement ('A', 'E' etc)