How to validate the String is in alphabetical order or not? It is just to validate that String is in order or not?
Can anybody help me how to validate? Here is my code::
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]);
}
}
}
You could get the i-th (i >= 1) element and apply compareTo(String other) against the previous one:
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With