我试图在一个数组中的特定单词中连续找到最多的辅音。我在评论中间有一个while循环,但由于某种原因它不会执行。有谁知道为什么?你也可能会注意到我有一个int空格,因为我试图找到一个String []字的子数组。我怎么可能这样做?
import java.io.*;
import java.util.*
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
System.out.print("Please enter a phrase to translate: ");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
String[] words = str.split("\\s+");
int spaces = (word.length - 1);
for (int i = 0; i < words.length; i++)
{
String a = words[i].substring(0,1);
int k = a.length();
int n = words[i].length();
if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
while (k < 5) // start while
{
if (n > k)
{
a = words[i].substring(0,k);
k = k + 1;
}
}
} // end while
if (words[i].startsWith("a") || words[i].startsWith("e") || words[i].startsWith("i") || words[i].startsWith("o") || words[i].startsWith("u"))
{
System.out.print(words[i] + "way");
}
else if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
String answer = words[i].substring(k,n);
System.out.print(answer + a + "ay");
}
}
}
}
答案 0 :(得分:0)
鉴于你的描述“试图在一个阵列中的特定单词中连续找到最多的辅音”,我会认为沿着这些线(未编译或测试 - 只是为了显示方法)的某些内容将是更容易遵循/调试/测试/维护(也只关注当前的word[i]
- 仍然需要一个迭代你的单词的外部循环:
String consgroups[] = word[i].split("[aeiou]"); // split on all vowels
int maxlen = consgroups[0].length, maxidx = 0;
for (int j = ; j < consgroups.length; ++j) // iterate over groups and find max
if (consgroups[j].length > maxlen)
{ maxidx = j;
maxlen = consgroups[i].length;
}
鉴于你对猪拉丁的评论,我不确定为什么除了这个词的开头以外的辅音小组很重要,但也许我误解了你的描述......
编辑:既然我看起来有点困难,我认为这种方法可能更有用:
String vowels = "aeiou";
int i = 0;
while ((i < word.length) && (!vowels.contains(word.subSequence(i, i + 1))))
++i;
// now word[i] is the first non-vowel character in word
if (i == word.length) // word was all consonants
{ ...
}
else
if (i) // word has a consonant prefix
{ ...
}
else // word starts with a vowel
{ ...
}