gpt4 book ai didi

java - 使用 .charAt 时缺少 return 语句

转载 作者:行者123 更新时间:2023-12-02 06:36:36 26 4
gpt4 key购买 nike

我需要编写一个返回单词中元音数量的代码,我的代码中不断出现错误,要求缺少返回语句。请问有什么解决办法吗? :3

import java.util.*;

public class vowels
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please type your name.");
String name = input.nextLine();
System.out.println("Congratulations, your name has "+
countVowels(name) +" vowels.");
}
public static int countVowels(String str)
{
int count = 0;
for (int i=0; i < str.length(); i++)
{
// char c = str.charAt(i);
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'o' || str.charAt(i) == 'i' || str.charAt(i) == 'u')
count = count + 1;
}
}
}

最佳答案

正如一些评论指出的那样,您缺少 return 语句。

您需要返回计数

public static int countVowels(String str)
{
int count = 0;
for (int i=0; i < str.length(); i++)
{
// char c = str.charAt(i);
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'o' ||
str.charAt(i) == 'i' || str.charAt(i) == 'u')
count = count + 1;
}

return count;
}

关于java - 使用 .charAt 时缺少 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19576921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com