我已经写了第一部分的代码,但是它计算了包括重复的元音的数量,但我也想知道如何计算没有重复的元音的数量。
我也在努力写代码的第二部分,即报告元音的总和。
这是我到目前为止所写的内容:
import java.io.*;
public class CountVowel {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
String s = br.readLine();
int l = s.length();
char ch;
int i;
int count = 0;
for(i = 0; i < l; i++)
{
ch = s.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
count=count+1;
}
}
System.out.println("The number of vowels are:"+count);
}
}
最佳答案
简单地说,您尝试使用不存储任何重复项的Set interface
,使用以下代码,
public static void main(String[] args) throws IOException {
Set<Character> set = new HashSet<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
String s = br.readLine();
int l = s.length();
char ch;
int i;
int count = 0;
for (i = 0; i < l; i++) {
ch = s.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
set.add(ch);
}
}
System.out.println("The number of vowels are:" + set.size());
}
关于java - 如何避免计算重复的元音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307912/