java - 不知道如何修复此错误,尝试编写一个方法但不断收到相同的错误

标签 java

我正在尝试编写一个方法,它将返回字符串“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/

相关文章:

java - zip 命令在 Java 代码中未按预期工作

java - Win64-JNI : UnsatisfiedLinkError: Can't find dependent libraries

java - 使用 tomcat 服务器的 Web 服务客户端缓存

java - Jackson 从值构建 JSON,术语?

java - 如何正确地将对象显示为字符串

java - 在 Bash 中使用 JAR 文件

java - 管理文件java上的大数组

java - 使用 Java 8 时间 API 根据当前日期在三个月内填充一周的最后几天(周一至周日)的 arrayList

java - 与 Camel 集成的基于 REST 的服务中的 API 版本管理

java - 在 Java/Kotlin 中跟踪递归方法