Java:字符串中的元音数量

丁尼丁

我被要求用以下方法编写一个NumberOcc类:

-方法getNbOcc,它将字符串str和字符'c'作为参数,并返回字符'c'的出现次数。

-方法dspNbOcc,显示getNbOcc返回的值

-method getNbVoy,它返回字符串str中的元音数量

-方法dspNbVoy,显示getNbVoy返回的值

问题是getNbVoy返回的值是错误的,例如:对于str = stackexchange它返回34个元音。

public class NumberOcc {
static int count1=0;
static int count2=0;
public static int getNbOcc(String str, char c) {
    for(int i=0;i<str.length();i++) {
        if (str.charAt(i)==c) 
                count1++;}
return count1;
    }
public static void dspNbOcc() {
    System.out.println(count1);
}
public static int getNbVoy(String str) {
    String vowel="aeiouy";
    
    for(int j=0;j<vowel.length();j++) { 
    
        count2+=getNbOcc(str,vowel.charAt(j));}
        return count2;
  }
public static void dspNbVoy() {
    System.out.println(count2);
}
}

测试类

public class TestNumberOcc {

    public static void main(String[] args) {
    String str="stackexchange";
    NumberOcc.getNbOcc(str, 'e');
    NumberOcc.dspNbOcc();
    NumberOcc.getNbVoy(str);
    NumberOcc.dspNbVoy();
        
        

    }

}

感谢您的帮助

艾略特新鲜

删除static字段,将值传递给方法。并使用它们显示结果。喜欢,

public static int getNbOcc(String str, char c) {
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == c) {
            count++;
        }
    }
    return count;
}

public static void dspNbOcc(String str, char c) {
    System.out.println(getNbOcc(str, c));
}

public static int getNbVoy(String str) {
    int count = 0;
    char[] vowels = "aeiouy".toCharArray();
    for (char ch : vowels) {
        count += getNbOcc(str.toLowerCase(), ch);
    }
    return count;
}

public static void dspNbVoy(String str) {
    System.out.println(getNbVoy(str));
}

然后测试一切就像

public static void main(String[] args) {
    String str = "stackexchange";
    NumberOcc.dspNbOcc(str, 'e');
    NumberOcc.dspNbVoy(str);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章