首页 > 解决方案 > 创建一种决定单词元音和声的方法

问题描述

    public static String vowelHarmony(String input) {

    String[] high = {"e", "i"};
    String[] deep = {"a", "o", "u"};

    for (int i = 0; i < input.length(); i++) {
        if (input.contains(high[i])&&!input.contains(deep[i])){
            return "high";
        }
        else if (input.contains(deep[i])&&!input.contains(high[i])){
            return "deep";
        }
        else if (input.contains(deep[i])&&input.contains(high[i])){
            return "mixed";
        }
    }
    return "you screwed something up";
}

我知道,我知道,英语中不存在元音和谐,但为了这个例子,让我们假装它存在。high元音是“e”和“i” 。元音是“ deepa”、“o”和“u”。所有单词都属于highdeepmixed

例如:

唯一的问题是,我的代码无法正常工作。如果单词是 ,它永远不会显示mixed。如果一个单词中甚至有一个大写字母,它会显示为high. 我需要做什么来修复它?我的代码有什么问题?

标签: javastring

解决方案


如前所述,代码存在两个问题:

  • 一旦第一次出现满足任何条件(这就是它正在检查的全部 - 第一次出现) - 你会得到你的结果。
  • 如果您的输入比您的任何一个字母数组都长(确实如此),您将获得一个ArrayIndexOutOfBoundsException.

在这种情况下,最好的办法是直接检查元音等价性,而不是依靠数组来存储它。

private static boolean hasHighVowel(String input) {
    return input.contains("e") || input.contains("i");
}

private static boolean hasLowVowel(String input) {
    return input.contains("a") || input.contains("o") || input.contains("u");
}

然后你可以在你的方法中检查它。还要注意不要立即从该方法返回。

 public static String vowelHarmony(String input) {
    String result = "you screwed something up";

    if (hasHighVowel(input)) {
        result = "high";
    }
    if (hasLowVowel(input)) {
        result = "deep";
    }
    if (hasHighVowel(input) && hasLowVowel(input)) {
        result = "mixed";
    }

    return result;
}

错误处理案例——例如当用户在null这个方法中输入或一个空字符串时——留给读者作为练习。


推荐阅读