Rules not obeyed by if statement - java

The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}

Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.

Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}

Related

Error counting vowels and consonant progr [duplicate]

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

Java, The loop doesn't start over from the beginning of the program [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am just finishing my program, but I still have one problem left that I can't seem to find an answer too. I have been looking through already asked questions but I couldn't find something that specifically answers my question in this case. This is a program that lets the user input a string and then it counts how many vowels and consonants etc. And after this the user gets an option to repeat the program and input a new string if he/she press y, the program quits if he/she press n etc. The only thing that is not working is if the user presses y to repeat the program, it then prints out that there are 0 vowels and consonants etc. I know that it is something in the beginning of my code where I have int consonant_count=0 for example, I just can't figure out what to move and where to move it. Ps. this shouldn't be flagged as a duplicate since I didn't know that nextLine was the problem. Here is the code:
import java.util.Scanner;
public class loop2
{
public static void main (String[] args)
{
Scanner inputReader = new Scanner (System.in);
char result='y';
do {
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.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 if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
// Kod f ̈or hantering av repetition
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.next();// H ̈amta anv ̈andarens svar.
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
result='y';
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
}
while (result == 'y'); // Observera semikolon!
}
}
You should use the nextLine() when reading input from the user, this grabs everything including the end of line character '\n' which is what gets left over after your next() call and then nextLine() grabs the '\n' which gives you the counts of 0, 0 for vowels and consonents
Scanner inputReader = new Scanner (System.in);
char result='y';
while(result == 'y')
{
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.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 if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
//wrap your play again logic in another do/while where you
// ask for y or n until they enter either one
do {
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.nextLine();//read the entire next line <----
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
} while (result !='y' && result !='n');
}

Keep Prompting Input From User

I have an assignment to do. I need to convert alphabets to telephone numbers. Add hyphen after the 3rd number and after every subsequent 4 numbers. Then I need to allow user to keep on entering input.
I've already gotten 3/4 of my codes done. It's not working. I'm only stuck with the part to keep prompting user for input.
This is my java code so far. Please help me and tell me what's wrong with my code. I'm new to Java, please be nice. Thank you!
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter letters: ");
String phonenumber = input.next();
String phone = phonenumber.replaceAll("\\s", " ");
int count = 0;
int prevCount = 0;
while (!phone.equals("#")){
for (int i = 0; i < phone.length(); i++)
{
char letter = Character.toLowerCase(phone.charAt(i));
if (letter == 'a' || letter == 'b' || letter == 'c')
{
System.out.print(2);
count++;
}
if (letter == 'd' || letter == 'e' || letter == 'f')
{
System.out.print(3);
count++;
}
if (letter == 'g' || letter == 'h' || letter == 'i')
{
System.out.print(4);
count++;
}
if (letter == 'j' || letter == 'k' || letter == 'l')
{
System.out.print(5);
count++;
}
if (letter == 'm' || letter == 'n' || letter == 'o')
{
System.out.print(6);
count++;
}
if (letter == 'p' || letter == 'q' || letter == 'r' || letter == 's')
{
System.out.print(7);
count++;
}
if (letter == 't' || letter == 'u' || letter == 'v')
{
System.out.print(8);
count++;
}
if (letter == 'w' || letter == 'x' || letter == 'y' || letter == 'z')
{
System.out.print(9);
count++;
}
if (count == 3 || count - prevCount == 4)
{
System.out.print('-');
prevCount = count;
}
}
System.out.println();
System.out.println("Enter letters: ");
input.nextLine();
}
}
use a loop:
while (true)
{
System.out.println("Enter letters: ");
String phonenumber = input.next();
if something break;
or
while ((String phonenumber = input.next())!=null)
{
// ...
System.out.println("Enter letters: ");
}
Your problem is here :
System.out.println();
System.out.println("Enter letters: ");
input.nextLine(); // you forgot to assign the String returned by nextLine
// into your phone variable
Beside that, you should reset your counters in each iteration of the while loop.
while (!phone.equals("#")) {
int count = 0;
int prevCount = 0;
... your for loop ...
System.out.println();
System.out.println("Enter letters: ");
phone = input.nextLine();
}

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.

Sorting data file by number of vowels

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)

Categories