Reputation: 29
I'm trying to write a method where it will return an integer value of where the first vowel is located in the string "w". I've already created the fist method to find if there is a vowel at a certain location, but when I tried using that method in the new method it says "cannot find symbol - method isVowel()." Does anyone know why this is and how to fix it? I've been told already that I must use the method isVowel in the new method. The error highlights the term "isVowel()" that is used in the last method.
public class words
{
private String w;
/**
* Default Constructor for objects of class words
*/
public words()
{
// initialise instance variables
w="";
}
/**
* Assignment constructor
*/
public words(String assignment)
{
w=assignment;
}
/**
* Copy constructor
*/
public words(words two)
{
w=two.w;
}
/**
* Pre: 0<=i<length( )
* returns true if the character at location i is a vowel (‘a’, ‘e’, ‘i', ‘o’, ‘u’ only), false if not
*/
public boolean isVowel(int i)
{
if (w.charAt(i)=='a')
return true;
else if (w.charAt(i)=='e')
return true;
else if (w.charAt(i)=='i')
return true;
else if (w.charAt(i)=='o')
return true;
else if (w.charAt(i)=='u')
return true;
else return false;
}
/**
* determines whether the first vowel in the String is at location 0, 1, 2, or 3 (don’t worry about exceptions)
*/
private int findFirstVowel()
{
return w.indexOf(w.isVowel());
}
Upvotes: 0
Views: 65
Reputation: 4084
Another possibility is also:
public boolean isVowel(int i)
{
char ch = Character.toLowerCase(w.charAt(i));
switch(ch) {
case 'a: case'e': case'i': case 'o': case 'u':
return true;
}
return false;
}
Also, 'y' is often a vowel. Your algorithm gives the incorrect number of vowels for words like "system", "syzygy", "why", etc.
Upvotes: 0
Reputation: 201409
You need to iterate the valid indices of w
, and then you can use your isVowel(int)
method to check. Something like,
private int findFirstVowel()
{
for (int i = 0; i < w.length(); i++) {
if (isVowel(i)) {
return i;
}
}
return -1;
}
Also, you might consider reducing your if-else
chain to a basic return
in isVowel
(and I note you currently only match lower-case letters, but we could also make it case-insensitive). Like,
public boolean isVowel(int i)
{
char ch = Character.toLowerCase(w.charAt(i));
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
Upvotes: 1