In: Computer Science
Write a java program to read a string from the keyboard, and count number of digits, letters, and whitespaces on the entered string. You should name this project as Lab5B.
This program asks user to enter string which contains following characters: letters or digits, or whitespaces. The length of the string should be more than 8. You should use nextLine() method to read string from keyboard.
You need to extract each character, and check whether the character is a letter or digit or whitespace.
You can access character at a specific index using charAt() method. Once you have extracted the character, you can test the extracted character using character test methods.
You can look at google/web search to check the methods (isDigit, isLetter, and isSpaceChar) available to test a character. Use the syntax properly in your code.
Once you found a match, simply increase the value of the counter by 1. You need 3
separate counters to count letters, digits, and spaces.
In this program, you do not need to worry about uppercase or lowercase letter.
Sample Output 1
Enter the string: EEEEEEE RRR LLLLLL UUUUUUUUUU Number of spaces: 3 Number of letters: 26 Number of digits: 0
import java.util.*;// util package is used for using Scanner class
class Lab5B {
public static void main (String[] args) {
String str;// variable to store string entered
int d_count=0,l_count=0,s_count=0,len;//variables for digit count,letter count,space count and length
Scanner s= new Scanner(System.in);//used to read string from keyboard
System.out.println("Enter the string");
str=s.nextLine(); // Reading the string
len=str.length(); // Calculating the length of the string
if(len<=8)// if length of string is less than or equal to 8 then this message is printed
System.out.println("Enter the string with length more than 8");
else// if length of string is more than 8 else is executed
{
for(int i=0;i<len;i++)// loop iterates from index 0 to length of string
{
char c=str.charAt(i); // extracting the character present at ith index
if(Character.isLetter(c))// isLetter is used to determine whether the character is alphabet or not
l_count++;// incrementing letters count
else if(Character.isDigit(c))//isDigit is used to determine whether the character is digit or not
d_count++;//if it is digit then digit count is incremented
else if(Character.isSpaceChar(c))//isSpaceChar is used to determine whether the character is space(" ") or not
s_count++;// if space then incrementing the space count
}
System.out.println("Number of spaces: "+s_count);
System.out.println("Number of letters: "+l_count);
System.out.println("Number of digits: "+d_count);
}
}
}
Please comment if you have any doubts.
Rate please!!!!!