英文:
How to count uppercase vowels and lowercase vowels in a string one time input?
问题
我已经创建了一个用Java编写的程序来计算小写元音字母的数量,但我无法计算大写元音字母。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入字母:");
char x = input.next().charAt(0);
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' ||
x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') {
System.out.println("元音字母");
} else {
System.out.println("辅音字母");
}
}
请注意,我在条件中添加了大写元音字母的检查。
英文:
I have created a program in Java to count lowercase vowels, but I'm not able to count uppercase vowels.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
//String input = new String(input.toUpperCase(0));
System.out.print("Enter tha Letter: ");
char x = input.next().charAt(0);
if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u'){
System.out.println("Vowel");
}else{
System.out.println("Consonant");
}
}
答案1
得分: 2
你可以使用包含元音字母的字符串,然后检查它是否包含输入的第一个字符:
Scanner input = new Scanner(System.in);
String vowels = "aeiouAEIOU";
System.out.print("Enter the Letter: ");
char x = input.next().charAt(0);
if (vowels.contains(Character.toString(x))) {
System.out.println("Vowel");
} else {
System.out.println("Consonant");
}
input.close();
或者,将 vowels
缩减为 "aeiou"
,并将输入字符转换为小写,使用 Character.toString(x)
。但我个人更喜欢另一种方式。
英文:
You could have a string containing your vowels and then check whether it contains the first char of the input:
Scanner input = new Scanner(System.in);
String vowels = "aeiouAEIOU";
System.out.print("Enter tha Letter: ");
char x = input.next().charAt(0);
if(vowels.contains(Character.toString(x))){
System.out.println("Vowel");
}else{
System.out.println("Consonant");
}
input.close();
Alternatively, reduce vowels
to "aeiou"
and lowercase the input character using Character.toString(x)
. But I personally like the other way better.
答案2
得分: 2
只返回翻译好的部分:
你可以创建一个最终的字符串 aeiouAEIOU
并搜索和检查它是否是元音。
由于 aeiouAEIOU
的长度固定,检查元音的时间复杂度为 O(1)
。
英文:
You can create a final string of aeiouAEIOU
and search and check if its a vowel
Since aeiouAEIOU
has a fixed length the time complexity to check for a vowel is O(1)
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
//String input = new String(input.toUpperCase(0));
System.out.print("Enter tha Letter: ");
String x = input.next().substring(0, 1);
final String vowels = "aeiouAEIOU";
if(vowels.contains(x)){
System.out.println("Vowel");
}else{
System.out.println("Consonant");
}
}
答案3
得分: 1
您可以简单地将大写元音字母的条件附加到您现有的if条件中:
if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A' || x=='E' || x=='I' || x=='O' || x=='U'){
System.out.println("元音");
}
英文:
You can simply append the conditions for Uppercase vowels in your existing if condition :
if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A' || x=='E' || x=='I' || x=='O' || x=='U'){
System.out.println("Vowel");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论