java - 创建一种决定单词元音和声的方法
问题描述
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” 。元音是“ deep
a”、“o”和“u”。所有单词都属于high
组deep
或mixed
。
例如:
- 如果一个词只有
high
元音,那么它就是一个high
词(hell、hill、mill、kill 等) - 如果一个词只有
deep
元音,它就是一个deep
词(sword、hold、stool、cool等) - 如果一个词同时包含两个组的元音,那么它就是一个
mixed
词(mule、mountain、house、choose 等)
唯一的问题是,我的代码无法正常工作。如果单词是 ,它永远不会显示mixed
。如果一个单词中甚至有一个大写字母,它会显示为high
. 我需要做什么来修复它?我的代码有什么问题?
解决方案
如前所述,代码存在两个问题:
- 一旦第一次出现满足任何条件(这就是它正在检查的全部 - 第一次出现) - 你会得到你的结果。
- 如果您的输入比您的任何一个字母数组都长(确实如此),您将获得一个
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
这个方法中输入或一个空字符串时——留给读者作为练习。
推荐阅读
- javascript - 反应表不显示数据
- c++ - 涉及依赖注入时如何使用组合而不是继承?
- android - W/SyncTree:在 /users 处侦听失败:DatabaseError:权限被拒绝
- android - 在某些设备上未获得适用于 Android 图像的 reCAPTCHA
- android - 将时间选择器限制为两个小时之间的时间选择
- angular - Angular 2 ViewChild NgModel 设置新值
- php - 如何使用 PHP 将变量从一个页面传递到另一个页面?
- sql - 从 JSON 列中的数组获取数据作为行
- php - Dropzone JS表单数据不发布到数据库
- python - pandas idxmax:在平局的情况下返回所有行