Reputation: 67
This pulls from a word bank our teacher gave us, and I'm supposed to return the longest word without vowels. But it either returns a word with vowels or nothing at all. Please Help.
//What is the longest word with no vowels (counting y as a vowel)?
public static void Question7()
{
// return the number of words in wordlist ending in "ing"
String longestWordSoFar = " ";
System.out.println("Question 7:");
int numberOfWords = 0; //count of words ending in ing
for(int i = 1; i < WordList.numWords(); i++) // check every word in wordlist
{
if(noVowel(WordList.word(i))) { // if the length is greater than the previous word, replace it
{
if(WordList.word(i).length() > longestWordSoFar.length())
longestWordSoFar=WordList.word(i);
}
}
}
System.out.println("longest word without a vowel: " + longestWordSoFar);
System.out.println();
return;
}
public static boolean noVowel(String word) {
//tells whether word ends in "ing"
for(int i = 0; i < word.length(); i++) {
//doesnt have a vowel - return true
if (word.charAt(i) != 'a') {
return true;
}
if (word.charAt(i) != 'e') {
return true;
}
if (word.charAt(i) != 'i') {
return true;
}
if (word.charAt(i) != 'o') {
return true;
}
if (word.charAt(i) != 'u') {
return true;
}
if (word.charAt(i) != 'y') {
return true;
}
}
return false;
}
Upvotes: 0
Views: 106
Reputation: 19766
in your method noVowel
, you return true
as soon as you find a character that is not a
,e
,i
,o
,u
, or y
. This is wrong. You'd rather return false
as soon as you find one of these characters and only return true
when there is none of them in the word.
Like this:
public static boolean noVowel(String word) {
for(int i = 0; i < word.length(); i++) {
//if a vowel found then return false
if (word.charAt(i) == 'a') {
return false;
}
if (word.charAt(i) == 'e') {
return false;
}
if (word.charAt(i) == 'i') {
return false;
}
if (word.charAt(i) == 'o') {
return false;
}
if (word.charAt(i) == 'u') {
return false;
}
if (word.charAt(i) == 'y') {
return false;
}
}
return true; // No vowel found, return true
}
Upvotes: 3
Reputation: 21961
Change your noVowel method like:
public static boolean noVowel(String word) {
boolean noVowel=true;
for(int i=0;i<word.length();i++){
char ch=word.charAt(i);
if(ch=='a' ||ch=='e' ||ch=='i' ||ch=='o' ||ch=='u' ||ch=='y'){
noVowel=false;
break;
}
}
return noVowel;
}
Upvotes: 0