w3resource

Java: Check if each letter of a given word is less than the one before it

Java Basic: Exercise-248 with Solution

From Wikipedia, An abecedarium (or abecedary) is an inscription consisting of the letters of an alphabet, almost always listed in order. Typically, abecedaria (or abecedaries) are practice exercises.
Write a Java program to check if each letter of a given word (Abecadrian word) is less than the one before it.

Sample Solution:

Java Code:

 // Importing necessary classes from the java.util package
import java.util.*;

// Defining a class named "solution"
public class solution {

    // Method to check if a word is an abecedarian word
    public static boolean is_abecedarian_word(String word) {
        // Finding the index of the last character in the word
        int index = word.length() - 1;

        // Looping through the characters of the word
        for (int i = 0; i < index; i++) {
            // Comparing the current character with the next one
            if (word.charAt(i) <= word.charAt(i + 1)) {
                // If the current character is less than or equal to the next one, continue
            } else {
                // If the current character is greater than the next one, return false
                return false;
            }
        }
        // If the loop completes without returning false, return true
        return true;
    }

    // Main method, the entry point of the program
    public static void main(String[] args) {
        // Creating a Scanner object for user input
        Scanner scanner = new Scanner(System.in);

        // Prompting the user to input a word
        System.out.print("Input a word: ");
        // Reading the input word from the user
        String word1 = scanner.nextLine();

        // Printing whether the input word is an abecedarian word
        System.out.println("Is Abecedarian word? " + is_abecedarian_word(word1));
    }
}

Sample Output:

Input a word:  ABCD
Is Abecadrian word? true

Flowchart:

Flowchart: Check if each letter of a given word is less than the one before it.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program which accepts three integers and check whether sum of the first two given integers is greater than third one. Three integers are in the interval [-231, 231 ]
Next: Write a Java program to count the number of set bits in a 32-bit integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/basic/java-basic-exercise-248.php