In: Computer Science
Write a Java test program, all the code should be in a single main method, that prompts the user for a single character. Display a message indicating if the character is a letter (a..z or A..Z), a digit (0..9), or other.
Java's Scanner class does not have a nextChar method. You can use next() or nextLine() to read the character entered by the user, but it is returned to you as a String. Since we are only interested in the first character, the character at position 0, you can use the following line of code to get just the first character out of the String returned by Scanner.
char c = input.charAt(0);
Unlike Strings, you can compare characters using relational operators. Recall that that the characters are in sequence; A comes before B, and B comes before C, etc. It's legal to write the following code in Java:
if ( c > 'A' && c < 'Z' )
This tests to see if c is a capital letter.
import java.util.Scanner;
class TestCharacter
{
public static void main (String[] args)
{
Scanner input = new
Scanner(System.in);
System.out.println("Enter a
character : ");
char c =
input.nextLine().charAt(0);
if(c >= 'A' && c <=
'Z')
System.out.println(c +" is capital
letter.");
else if(c >= 'a' && c
<= 'z')
System.out.println(c +" is small
letter.");
else if(c >= '0' && c
<= '9')
System.out.println(c +" is a
digit.");
else
System.out.println(c +" is other
special character.");
}
}
Output:
Enter a character : $ $ is other special character.
Enter a character : l l is small letter.
Enter a character : 8 8 is a digit.
Enter a character : F F is capital letter.
Do ask if any doubt. Please up-vote.