JO_VIC
JO_VIC

Reputation: 13

using a boolean method to return true if the string inputed is alphabetically arranged

I'm writing a program that takes a string and returns a boolean indicating whether the word is alphabetically arranged e.g. abdest, acknow, adempt etc.

My problem is that the program returns no output but just terminates... Please I would really appreciate some corrections. Here is my code:

public class test{ 
    public static boolean Abecedarian(String s) {
        String alp="";
        for(char c ='A'; c<='Z'; c++){ 
            alp +=c; 
        }           
        if(s.equals(alp)){ 
            return true; 
        }else 
            return false; 
        } 
    public static void main(String[] args) { 
        Abecedarian("victor"); 
    } 
}

Upvotes: 0

Views: 1121

Answers (1)

David P&#233;rez Cabrera
David P&#233;rez Cabrera

Reputation: 5048

Try with this:

public static void main(String[] args) {
    String [] words = {"abdest", "acknow", "adempt" };
    for (String word : words) {
        System.out.println(" isAbecedarian '"+word+"': "+isAbecedarian(word));
    }
}

public static boolean isAbecedarian(String s) {
    if (s == null ) throw new IllegalArgumentException("Error");
    if (s.length() < 2) return true;
    char last = s.charAt(0);
    char current;
    for (int i = 1; i < s.length(); i++) {
        current = s.charAt(i);
        if (current < last) {
            return false;
        }
        last = current;
    }
    return true;
}

output:

isAbecedarian 'abdest': true
isAbecedarian 'acknow': true
isAbecedarian 'adempt': true

Upvotes: 1

Related Questions