-1

我必须检查一个单词/短语,并说出其中的元音是按字母顺序排列还是按字母顺序倒序排列。我很接近得到它。它只是比较数组中的数字的最后一点,看看它们是否按降序排列等。我知道我必须做一个嵌套的 for 循环,但我不确定该怎么做。谢谢您的帮助。

public static void main(String [] args)
{


    String result = "", result2="";                                 
    String userInput = "aeiou";
    int [] array = new int[userInput.length()];


    for(int i = 0; i < string.length(); ++i) 
    {

        char c = replace.charAt( i );
        int j = (int) c;
        array[i] = j;

        //printing unicode symbols (only for testing)
        result2 += array[i] +",";
        System.out.println(j);
    }

    boolean sequence = false;
    for(int i = 0; i <array.length-1 && !sequence; i++)
    {
        for(int x =i+1; x<array.length; x++)
        {
            //Here I am checking to see whether or not they are in alphabetical order
            if(array[i] < array[x])
            sequence = true;
            if(sequence == true)
                result = "The vowels are  in  alphabetical order";
            else
                result = "The vowels are not in alphabetical order";
        }
    }

    System.out.println(result);
}
4

2 回答 2

1

由于您使用的是replaceAll(),我假设您也可以使用matches()(replace是替换除元音以外的所有内容后包含字符串的变量):

boolean isAscending = replace.matches("a*e*i*o*u*");
boolean isDescending = replace.matches("u*o*i*e*a*");

好吧,这里有一些特殊情况似乎没有在您的代码中考虑:

  • replace变量中的字符串为空(无元音)
  • 仅包含一个重复的元音(例如pool--> oo

在上述两种情况下,isAscendingisDescending将是true.

于 2013-02-16T20:31:41.213 回答
0

尝试

    String input = "abc";
    char[] a = input.toCharArray();
    Arrays.sort(a);
    StringBuilder sb = new StringBuilder();
    sb.append(a);
    if (input.equals(sb.toString())) {
        System.out.println("ascending");
    } else if (input.equals(sb.reverse().toString())) {
        System.out.println("descending");
    } else {
        System.out.println("unsorted");
    }
于 2013-02-17T02:05:00.050 回答