我无法让我的元音计数器在我为此上限创建的 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/