java - Java元音计数器的问题

标签 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++;
        }
    }

}

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

最佳答案

您的 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;
}

关于java - Java元音计数器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38236585/

相关文章:

java - ResourceBundle/Properties 文件接受参数 {0} 中的字符串数组

java - System.out.println 和 System.err.println 乱序

java - 接口(interface)常量有什么用?

java - 为什么 for(T t : this) work and what does it mean?

javascript - 循环更改数组并从先前添加的项目开始

javascript - 如何解析(无限)嵌套对象符号?

java - HTTP请求实时应用,性能技巧

java - 在 Spring boot 中捕获 JDBCConnectionException

postgresql - 用随机等级更新表

python 动态字典