Java元音计数器的麻烦

时间:2016-07-07 02:04:12

标签: java for-loop

我无法让我的元音计数器在我为此上限创建的for循环中运行。这是我的代码:

//java app that counts vowels using a forloop
import java.util.Scanner;
public class App {

public static void main(String[] args) {
Scanner ent=new Scanner(System.in);     
String string1; 
System.out.println("Entered a letter:");
string1 = ent.nextLine();}


public static int numberVowels(String string1){
    int count=0;
    int vowels=0;
    int consonants=0;
    for(int i=0; i<string1.length(); i++){

        char ch=string1.charAt(i);
        if(ch=='a' || ch=='e' ||ch=='i' ||ch=='o'||ch=='u' ){

            vowels++;
            return ch=ch+vowel;
        }else{

            consonants++;
        }
    }

}

}

它说没有返回类型,但我确实有返回类型。我做错了什么

2 个答案:

答案 0 :(得分:2)

你的if中有一个return语句(它看起来似乎很奇怪),你需要一个保证可以访问的;因为你的方法是计算vowels,你应该坚持这一点。最后,由于您只测试小写元音,我建议您在测试之前调用toLowerCase。像,

public static int numberVowels(String string1) {
    int vowels = 0;
    for (int i = 0; i < string1.length(); i++) {
        char ch = Character.toLowerCase(string1.charAt(i));
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            vowels++;
        }
    }
    return vowels;
}

使用for-each loop之类的

public static int numberVowels(String string1) {
    int vowels = 0;
    for (char ch : string1.toLowerCase().toCharArray()) {
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            vowels++;
        }
    }
    return vowels;
}

答案 1 :(得分:-1)

是的,有关Java语法的消息尝试使用此修复:

如果您的方法具有返回类型,则始终检查已返回变量的Java。

´

//java app that counts vowels using a forloop
import java.util.Scanner;
public class App {

public static void main(String[] args) {
Scanner ent=new Scanner(System.in);     
String string1; 
System.out.println("Entered a letter:");
string1 = ent.nextLine();}


public static int numberVowels(String string1){
    int count=0;
    int vowels=0;
    int consonants=0;
    char tmp='';
    for(int i=0; i<string1.length(); i++){

        char ch=string1.charAt(i);
        if(ch=='a' || ch=='e' ||ch=='i' ||ch=='o'||ch=='u' ){

            vowels++;
            tmp= ch=ch+vowel;
        }else{

            consonants++;
        }
    }
return tmp;
}

`

相关问题