gpt4 book ai didi

java - Java中如何统计字符串中辅音的个数?

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

我正在编写一个程序,用于计算用户输入的句子中元音和辅音的数量。我下面的代码计算了元音的数量,但它给了我奇怪的辅音计数。例如,如果我输入“g”,我得到的辅音计数为 10。

import java.util.Scanner;

public class VowelCount{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a sentence :");
String sentence = scan.nextLine();

String vowels = "aeiouAEIOU";
int vowelCount = 0;
int consCount = 0;
int i;

for(i = 0; i < sentence.length(); i += 1){
char currentChar = sentence.charAt(i);
int index;
for(index = 0; index < vowels.length(); index += 1){
if(vowels.charAt(index) == (currentChar)){
vowelCount++;
}else if(Character.isLetter(currentChar) && (vowels.charAt(index) == (currentChar))){
consCount++;
}
}
}
System.out.println(consCount);
System.out.println(vowelCount);
}
}

最佳答案

这有效。我还对其进行了改进,请参阅 vowels.indexOf (而不是手动迭代)以及带有 isLetter 的行(更正了对元音的错误检查)和输出(添加了 ; )和i++

public class VowelCount{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a sentence :");
String sentence = scan.nextLine();

String vowels = "aeiouAEIOU";
int vowelCount = 0;
int consCount = 0;
int i;

int length = sentence.length();
for(i = 0; i < length; i ++){
char currentChar = sentence.charAt(i);
if (vowels.indexOf(currentChar)>=0)
vowelCount++;
else if(Character.isLetter(currentChar))
consCount++;
}
System.out.print(consCount+";");
System.out.print(vowelCount);
}
}

关于java - Java中如何统计字符串中辅音的个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25262270/

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