How to write Pangram checker program in java using String?

     Pangram is a sentence which has all English alphabets at least once in it. Some of the examples of pangram sentences are given below.

  • ·       Brown jars prevented the mixture from freezing too quickly
  • ·       How vexingly quick daft zebras jump
  • ·       The quick brown fox jumps over a lazy dog

Let us create this program in java using String.

Steps:

  • ·       Import the built in packages java.util.HashSet,java.util.Set,java.util.Scanner.
  • ·       Create a class PangramCheckeralphabet.
  • ·       Member function: isitPangram ()
  • ü  This function takes the input as sentence to be checked.
  • ü  It checks the given sentence is null or not. If it is not null,then proceed the function.
  • ü  Create an object for HashSet.
  • ü  Check the sentence for all alphabets at least once.
  • ü  Return the number.
  • ·       Main() function:
  • ü  It creates a scanner object.
  • ü  Read the input from the user and pass it to isitPangram() function.
  • ü  Get the value from the function. if it is true, then print it is a pangram sentence.
  • ü  Otherwise, print it is not pangram sentence.

Program:

import java.util.HashSet;

import java.util.Set;

import java.util.Scanner;

//Creating a public class

public class PangramCheckeralphabet {

    public static boolean isitPangram(String asentence) {

        if (asentence == null) {

            return false;

        }

        Set<Character> alphabetSet = new HashSet<>();

        for (char c : asentence.toLowerCase().toCharArray()) {

            if (c >= 'a' && c <= 'z') {

                alphabetSet.add(c);

            }

        }

        return alphabetSet.size() == 26;

    }

//Main function

    public static void main(String[] args) {

        Scanner myObj1 = new Scanner(System.in);

        System.out.println("Enter the sentence to check for pangram");

        String asentence = myObj1.nextLine();

        if (isitPangram(asentence)) {

            System.out.println("Yes.It is a pangram sentence.");

        } else {

            System.out.println("No. It is not a pangram sentence.");

        }

}

}

Output:   

There are two outputs given below.

C:\raji\blog>javac PangramCheckeralphabet.java

C:\raji\blog>java PangramCheckeralphabet

Enter the sentence to check for pangram

Brown jars prevented the mixture from freezing too quickly

Yes.It is a pangram sentence.

 

C:\raji\blog>java PangramCheckeralphabet

Enter the sentence to check for pangram

It is a new sentence

No. It is not a pangram sentence.

This is one of the efficient way of creating pangram checker program in java. Try this with your input sentence and enjoy coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.