Consider what things would be like without the wrapper classes. How could we classify chars? For instance, alphabetic, numeric, alphanumeric. Or how could you convert between case?
public class CharEx {
public static void main(String[] args) {
char c;
c = 'a';
System.out.println(c);
if ( c >= '0' && c <= '9' )
System.out.println (c + " is a digit.");
if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') )
System.out.println (c + " is a letter.");
}
}
Now let's translate this into methods! We will create our own MyCharacter (to avoid collisions) and we will go one step further and add my as a prefix for the method names as well.
public class MyCharacter {
public static boolean isDigit(char c) {
return ( c >= '0' && c <= '9' );
}
public static boolean isLetter(char c) {
return ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') );
}
static boolean isLetterOrDigit(char c) {
return isLetter(c) || isDigit(c);
}
static char toUpperCase(char c) {
//... convert
return 0;
}
static char toLowerCase(char c) {
//... convert
return 0;
}
}
You may be thinking to yourself, why does the return statement look like that? Good question. We could have written:
if ( c >= '0' && c <= '9' )
return true;
else
return false;
But honestly, the expression already evaluates to boolean (true or false). So, we just return the evaluation.
Finally, here is an exerciser program to test the class:
import java.util.*;
public class Exerciser {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
char c;
System.out.print("Enter a character: ");
while ( kb.hasNext() ) {
c = kb.next().charAt(0);
if (MyCharacter.isDigit(c))
System.out.println(c + " is a digit!");
if (MyCharacter.isLetter(c))
System.out.println(c + " is a letter!");
System.out.print("Enter a character: ");
}
}
}
For you TO-DO: How would you complete the toUpperCase() and toLowerCase() methods?