Reputation: 25
I would like to keep my program pretty much the same.
I've used a lot of String methods like charAt
, substring
and indexOf
.
A word is said to be “abecedarian” if the letters in the word appear in alphabetical order.
import java.util.*;
public class Abecedarian{
public static void main( String[] args ){
String word=getWord();
}
public static String getWord(){
Scanner keyboard = new Scanner(System.in);
String word;
System.out.print("Enter a word: ");
word=keyboard.nextLine();
return word;
}
public static boolean isAbecedarian(String word){
Upvotes: 1
Views: 3341
Reputation: 311796
You could iterate over the characters in the word and make sure they are in ascending alphabetical order:
public static boolean isAbecedarian (String word) {
int length = word.size();
if (length <= 1) {
return true;
}
word = word.toLowerCase(); // just in case
char prev;
char curr;
for (int i = 1; i < length; ++i) {
prev = word.charAt(i - 1);
curr = word.charAt(0);
if (prev > curr) {
return false;
}
}
return true;
}
Upvotes: 2
Reputation: 37053
Try using:
if (word.compareTo("abecedarian") == 0) {
//yes it is equal
}
There's better way of checking for equality using equals
method of String like:
if ("abecedarian".equals(word)) {
...
}
Upvotes: 0