Sorting data file by number of vowels - java

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)

Related

How to check for vowels using a helper method and return a string in Java?

I am attempting to use a helper method that checks if all characters in a word are vowels.
I am then attempting to create another method that uses a Scanner as a parameter and will continuously ask the user to enter a word until the user enters a word that contains all vowels. (The word doesn't have to be a word, it could be ieuo).
I cannot figure out how to have the method verify the scanner is all vowels and then return the correct output.
Here is what I have so far:
import java.util.*;
public class LabFinish {
public static void main(String[] args) {
System.out.println("Enter a word: ");
Scanner scan = new Scanner(System.in);
askForWords(scan);
public static boolean isAllVowels(Scanner scan) {
String str = scan.nextLine();
for (int i = 0; i <= str.length(); i++)
if ((str.charAt(i) == 'a') ||
(str.charAt(i) == 'e') ||
(str.charAt(i) == 'i') ||
(str.charAt(i) == 'o') ||
(str.charAt(i) == 'u')) {
return true;
}
return false;
}
public static String askForWords(Scanner scan) {
if (isAllVowels(scan) == true) {
return "Finally all vowels, we are done.";
}
else {
System.out.println("Enter a word: ");
Scanner scan1 = new Scanner(System.in);
if (isAllVowels(scan1) == true) {
return "Finally all vowels, we are done.";
}
else {
return "Enter a word";
}
}
}
Any help with this would be greatly appreciated.
Thank you.
A couple of things that should help you forward:
Merely returning a String from a method doesn't output it anywhere. So, replacing
askForWords(scan);
with
System.out.println(askForWords(scan));
in main() will show you the result of the method.
While you're checking for vowels, you need to iterate through the whole word, instead of stopping at the first vowel you encounter. Using your current code, the easiest fix is to invert the values of the return statements and the truth value of the comparison:
for (int i = 0; i < str.length(); i++) {
if ( !( // <- if the string has any other characters than the ones below, return a falsey
(str.charAt(i) == 'a')
|| (str.charAt(i) == 'e')
|| (str.charAt(i) == 'i')
|| (str.charAt(i) == 'o')
|| (str.charAt(i) == 'u'))) {
return false;
}
}
return true;
You also have some other issues, such as the code only running for a maximum of two input strings (you'd need a loop instead of a single if-else), but these are a bit off-topic for this question.

Rules not obeyed by if statement

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

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.

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]++;
}
}
}
}

l33t why is it printing three U's

i am having a problem i am making a l33t translator and my translator from English to l33t works for my l33t to English works other then u and what is happening is it is printing three U's i have tryed taking it out of the for loop and it will only print one but it prints it at the start of the word i have tryed putting it at the bottom out of the for and it doesnt even print one. i have also tryed if(phrase.charAt(i) == '|') && phrase.charAt(i+1) == '_' && phrase.charAt(i+2) == '|'). here is what i got.
public static String translateToEnglish(String phrase) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello what pharse would you like to convert in to l33t");
phrase = scan.nextLine();
String NewString = "";
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == '4') {
NewString += "a";
}
if (phrase.charAt(i) == '8') {
NewString += "b";
} else {
if (phrase.charAt(i) == '3') {
NewString += "e";
}
}
if (phrase.charAt(i) == '1') {
NewString += "l";
} else {
if (phrase.charAt(i) == '0') {
NewString += "o";
}
}
if (phrase.charAt(i) == '5') {
NewString += "s";
} else {
if (phrase.charAt(i) == '7') {
NewString += "t";
}
}
if (phrase.contains("|_|")) {
NewString += "u";
}
if (phrase.charAt(i) == '2') {
NewString += "z";
}
if (phrase.charAt(i) == 'c' || phrase.charAt(i) == 'd' || phrase.charAt(i) == 'f' || phrase.charAt(i) == 'g'
|| phrase.charAt(i) == 'h' || phrase.charAt(i) == 'i'
|| phrase.charAt(i) == 'j' || phrase.charAt(i) == 'k' || phrase.charAt(i) == 'm' || phrase.charAt(i) == 'n'
|| phrase.charAt(i) == 'p' || phrase.charAt(i) == 'q'
|| phrase.charAt(i) == 'r' || phrase.charAt(i) == 'v' || phrase.charAt(i) == 'w' || phrase.charAt(i) == 'x'
|| phrase.charAt(i) == 'y') {
NewString += phrase.charAt(i);
}
// if (phrase.charAt(i) == 'c') {
}
System.out.println(NewString);
return phrase;
}
For every char in the word you check if it contains a "u". It will always be true because you don't check at a specific position of the word. You would have to check for a | followed by _ followed by | and then add a "u" instead of generally checking if it's somewhere in the input.
Your if statement for |_| is doing a String#contains comparison and is not elsed. So for every iteration in the loop it will print a u if the phrase contains this sequence of characters.
If you use your alternative of checking each char at i, i+1, i+2 you will firstly have to make sure that your phrase is long enough and then if it is true, in that if statement you will have to make sure you increment i by 3 i.e
if(phrase.length() < i+2
&& phrase.charAt(i) == '|')
&& phrase.charAt(i+1) == '_'
&& phrase.charAt(i+2) == '|')
{
NewString += "u";
i += 2; // Will get the third increment from loop
continue;
}
Also if you make sure the structure is always if..if else...else, the final check where is just replaces with the same character can just be reduced to an else without needing to or together every other character

Categories