简体   繁体   English

如何计算一次输入的字符串中的大写元音和小写元音?

[英]How to count uppercase vowels and lowercase vowels in a string one time input?

I have created a program in Java to count lowercase vowels, but I'm not able to count uppercase vowels.我在 Java 中创建了一个程序来计算小写元音,但我无法计算大写元音。

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");
    }
}

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) .或者,将vowels缩减为"aeiou"并使用Character.toString(x)将输入字符小写。 But I personally like the other way better.但我个人更喜欢另一种方式。

You can create a final string of aeiouAEIOU and search and check if its a vowel您可以创建aeiouAEIOU的最终字符串并搜索并检查它是否是元音

Since aeiouAEIOU has a fixed length the time complexity to check for a vowel is O(1)由于aeiouAEIOU具有固定长度,因此检查元音的时间复杂度为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");
        }
    }

You can simply append the conditions for Uppercase vowels in your existing if condition:您可以简单地 append 现有 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("Vowel");
}

I have created a program in Java to count lowercase vowels, but I'm not able to count uppercase vowels.我在 Java 中创建了一个程序来计算小写元音,但我无法计算大写元音。

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM