program to enter a string using scanner and find out the number of words,spaces,letters,numbers and special characters in it.
import java.util.Scanner;
public class Scan
{
  public static void main(String[] args)
  {
    Scanner sc = new Scanner(System.in);
    String s1;
    int i,len,space=0,letter=0,digit=0,punc=0;
    char ch;
   System.out.println("Enter a sentence:");
    s1 = sc.nextLine();
    len=s1.length();
    for(i=0;i< len;i++)
    {
         ch=s1.charAt(i);
         if(ch==' ')
         space++;
         else if((ch>=65 && ch< =90) ||(ch>=97 && ch< =122))
         letter++;
         else if(ch>=48 && ch< =57)
         digit++;
         else
         punc++;
        }
       System.out.println("Number of Words in the sentence="+(space+1));
       System.out.println("Number of spaces in the sentence="+space);   
       System.out.println("Number of letters in the sentence="+letter);
       System.out.println("Number of digits="+digit);
       System.out.println("Number of punctuations="+punc);
    }
}
Sample input and output:
Enter a sentence:
This is our first test
Number of Words in the sentence=5
Number of spaces in the sentence=4
Number of letters in the sentence=18
Number of digits=0
Number of punctuations=0
Enter a sentence:
Address is: 14,circular road
Number of Words in the sentence=4
Number of spaces in the sentence=3
Number of letters in the sentence=21
Number of digits=2
No comments:
Post a Comment