如何使用Java验证字符串数组是否按字母顺序排序?

3

如何验证字符串是否按字母顺序排列?这只是为了验证字符串是否按顺序排列。

有人可以帮我验证吗? 以下是我的代码:

public class Example3 {

    public static void main(String[] args) {

        String Month[]={"Jan", "Add", "Siri", "Xenon", "Cat"};

        for(int i=0; i<Month.length; i++) {     
            System.out.println(Month[i]);                   
        }
    }
}

你能澄清一下你所说的字母顺序是什么意思吗? - Tunaki
当我从任何下拉列表中获取文本时,我将获得所有选项的文本。我将这些值存储在一个字符串中,如下所示:String str = single.getText(); System.out.println(str); ---> str的输出为Jan,Add,Xenon。现在我想验证'str'是否有序。 - Chanakya
2个回答

6
您可以获取第 i 个(i >= 1)元素,并将 compareTo(String other) 应用于前一个元素:
boolean ordered = true;
for (int i = 1; i < month.length; i++) {
    if (month[i].compareTo(month[i - 1]) < 0) {
         ordered = false;
         break;
    }
}

System.out.println(ordered ? "Ordered" : "Unordered");

0

不需要循环,只需使用Collections进行比较,因为equals方法可以很好地处理这种类型的对象。


解决方案

String[] Month={"Jan", "Add", "Siri", "Xenon", "Cat"};
List<String> copyOf = new ArrayList<>(Arrays.asList(Month));
Collections.sort(copyOf);
if (Arrays.asList(Month).equals(copyOf)){
    System.out.println("Sorted");
} else {
    System.out.println("Not sorted"); // Not sorted of course but if Month
                                      // was {"Add", "Siri"} it would've been true
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接