0

我正在尝试为数组中的特定单词连续查找最多数量的辅音。我在中间有一个我评论过的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");
            }
        }
    }
}
4

1 回答 1

0

鉴于您对“尝试为数组中的特定单词连续查找最多数量的辅音”的描述,我认为这些方面的内容(未编译或测试 - 只是为了展示方法)会更简单follow/debug/test/maintain(也只查看当前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
  { ...
  }
于 2013-07-22T18:46:08.253 回答