我正在尝试编写一个方法,它将返回字符串“w”中第一个元音所在位置的整数值。我已经创建了第一个方法来查找某个位置是否有元音,但是当我尝试在新方法中使用该方法时,它说“找不到符号 - 方法 isVowel()”。有谁知道这是为什么以及如何解决它?我已经被告知我必须在新方法中使用 isVowel 方法。该错误突出显示了最后一个方法中使用的术语“isVowel()”。
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());
}
最佳答案
您需要迭代 w
的有效索引,然后可以使用 isVowel(int)
方法进行检查。比如,
private int findFirstVowel()
{
for (int i = 0; i < w.length(); i++) {
if (isVowel(i)) {
return i;
}
}
return -1;
}
此外,您可能会考虑将 if-else
链减少为 isVowel
中的基本 return
(我注意到您目前仅匹配较低的- 大小写字母,但我们也可以使其不区分大小写)。就像,
public boolean isVowel(int i)
{
char ch = Character.toLowerCase(w.charAt(i));
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
关于java - 不知道如何修复此错误,尝试编写一个方法但不断收到相同的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52977739/