如何计算我们的字符串有多少元音



我是Java的新手,我正在尝试解决一个挑战。我必须写一些单词,并比较哪个单词更长,以及一个元音越长。另外,如果您写" end",写单词以结束并打印其他东西,在我们的情况下,您没有写任何词。

终端中的输出示例(CMD):

写一个单词,或写入"结束"以结束写作:test
写一个单词,或写入"结束"到结束写作:TEE
写一个单词,或写入"结束"结束写作:测试
写一个单词,或写入"结束"到结束写作:end

单词测试最长,它具有2个元音。

输出示例,如果您不写任何字:

写一个单词,或写入"结束"以结束写作:
写一个单词,或写入"结束"以结束写作:
写一个单词,或写入"结束"到结束写作:end

您没有写任何单词。

应使用Scanner (Input)Switch CaseDo While对程序进行编码。应使用方法equalsIgnoreCase()比较字符串。

我尝试了很多次,而我所做的只是编写和删除代码。

这是我的代码:

import java.util.Scanner;
public class VowelFinder {
public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String word = null;
        int num = 0;
        String max = null;
        final String SENTINEL = "end";
        System.out.println(" ");
        do {
            System.out.print("Write a word, or write `" + SENTINEL + "` to end writing: ");
            word = scan.nextLine();
            if(!word.equalsIgnoreCase(SENTINEL)) {
                int nr = countVowels(word);
                if (num <= nr) {
                    num = nr;
                    max = word;
                }
            }
        } while (!word.equalsIgnoreCase(SENTINEL));
        if (max != null) {
            System.out.println(" ");
            System.out.println("Word `" + max + "` is longest word, and countains " + num + " vowels.");
        }
        else {
            System.out.println(" ");
            System.out.println("You din't wrote any word !");
        }
}   

private static int countVowels(String word) {
    int counter = 0;
    int vowels = 0;
    while(counter < word.length()){
        char ch = word.charAt(counter++);

        switch (ch) {
            //Lower Case
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
            case 'y':
            //Upper Case
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U':
            case 'Y':
            vowels++;
            default:
            // do nothing
        }
    }
    return vowels;
}
}

问题是:

当我在终端(CMD)

中这样做时

写一个单词,或写入"结束"以结束写作:
写一个单词,或写入"结束"以结束写作:
写一个单词,或写入"结束"到结束写作:end

它打印我 word''是最长的单词,countains 0元音。,但是它应该打印您没有写任何单词。

有人可以帮我吗?我在哪里做错了?

它应该打印我您没有写任何单词如果我不写任何字。

我希望我很清楚,你可以帮助我。如果我不清楚,请问我。

感谢您的贡献。

将if条件更改为

if (word != null && !"".equals(word.trim()) && !word.equalsIgnoreCase(SENTINEL))

我添加了null检查并进行了trim以删除白色空间。

我做了一些更改,对我有用...

if (max != null && !max.trim().isEmpty() && max.length()>0) {
            System.out.println(" ");
            System.out.println("Word `" + max + "` is longest word, and countains " + num + " vowels.");
        }

您可以在 countVowels()中检查当前单词是否没有。

private static int countVowels(String word) {
    int counter = 0;
    int vowels = 0;
    if(word.length() == 0){
        return  -1;
    }
    ...
}

返回值小于0,因此max不会被替换。

最新更新