AhmadLang / Java, How To Program, 2004
.pdf
Line 21 uses Character method isLetter to determine whether character c is a letter. If so, the method returns true, and otherwise, it returns false. Line 23 uses Character method isLetterOrDigit to determine whether character c is a letter or a digit. If so, the method returns true, and otherwise, it returns false.
Line 25 uses Character method isLowerCase to determine whether character c is a lowercase letter. If so, the method returns true, and otherwise, it returns false. Line 27 uses Character method
isUpperCase to determine whether character c is an uppercase letter. If so, the method returns true, and otherwise, it returns false.
[Page 1375]
Line 29 uses Character method toUpperCase to convert the character c to its uppercase equivalent. The method returns the converted character if the character has an uppercase equivalent, and otherwise, the method returns its original argument. Line 31 uses Character method toLowerCase to convert the character c to its lowercase equivalent. The method returns the converted character if the character has a lowercase equivalent, and otherwise, the method returns its original argument.
Figure 29.16 demonstrates static Character methods digit and forDigit, which convert characters to digits and digits to characters, respectively, in different number systems. Common number systems include decimal (base 10), octal (base 8), hexadecimal (base 16) and binary (base 2). The base of a number is also known as its radix. For more information on conversions between number systems, see Appendix E.
Figure 29.16. Character class static conversion methods.
(This item is displayed on pages 1375 - 1376 in the print version)
1// Fig. 29.16: StaticCharMethods2.java
2// Static Character conversion methods.
3import java.util.Scanner;
4
5public class StaticCharMethods2
6{
7// create StaticCharMethods2 object execute application
8 public static void main( String args[] )
9{
10Scanner scanner = new Scanner( System.in );
12// get radix
13System.out.println( "Please enter a radix:" );
14int radix = scanner.nextInt();
16// get user choice
17System.out.printf( "Please choose one:\n1 -- %s\n2 -- %s\n",
18"Convert digit to character", "Convert character to digit");
19int choice = scanner.nextInt();
20
21// process request
22switch ( choice )
23{
24case 1 : // convert digit to character
25 |
System.out.println( "Enter a digit:" ); |
26 |
int digit = scanner.nextInt(); |
27 |
System.out.printf( "Convert digit to character: %s\n", |
28 |
Character.forDigit( digit, radix )); |
29 |
break; |
30 |
|
31 |
case 2 : // convert character to digit |
32 |
System.out.println( "Enter a character:" ); |
33 |
char character = scanner.next().charAt( 0 ); |
34 |
System.out.printf( "Convert character to digit: %s\n", |
35 |
Character.digit( character, radix )); |
36 |
break; |
37} // end switch
38} // end main
39} // end class StaticCharMethods2
16else
17System.out.println( "c1 and c2 are not equal\n" );
18} // end main
19} // end class OtherCharMethods
c1 = A
c2 = a
c1 and c2 are not equal
[Page 1376 (continued)]
29.6. Class StringTokenizer
When you read a sentence, your mind breaks the sentence into tokensindividual words and punctuation marks, each of which conveys meaning to you. Compilers also perform tokenization. They break up statements into individual pieces like keywords, identifiers, operators and other elements of a programming language. In this section, we study Java's StringTokenizer class (from package java.util), which breaks a string into its component tokens. Tokens are separated from one another by delimiters, typically whitespace characters such as space, tab, newline and carriage return. Other characters can also be used as delimiters to separate tokens. The application in Fig. 29.18 demonstrates
class StringTokenizer.
[Page 1377]
Figure 29.18. StringTokenizer object used to tokenize strings.
(This item is displayed on page 1378 in the print version)
1// Fig. 29.18: TokenTest.java
2// StringTokenizer class.
3import java.util.Scanner;
4import java.util.StringTokenizer;
6public class TokenTest
7{
8// execute application
9public static void main( String args[] )
10{
11// get sentence
12Scanner scanner = new Scanner( System.in );
13System.out.println( "Enter a sentence and press Enter" );
14String sentence = scanner.nextLine();
15
16// process user sentence
17StringTokenizer tokens = new StringTokenizer( sentence );
18System.out.printf( "Number of elements: %d\nThe tokens are:\n",
19tokens.countTokens() );
20
21while ( tokens.hasMoreTokens() )
22System.out.println( tokens.nextToken() );
23} // end main
24} // end class TokenTest
Enter a sentence and press Enter This is a sentence with seven tokens Number of elements: 7
The tokens are: This
is a
sentence with seven tokens
When the user presses the Enter key, the input sentence is stored in String variable sentence. Line 17 creates an instance of class StringTokenizer using String sentence. This StringTokenizer constructor takes a string argument and creates a StringTokenizer for it, and will use the default delimiter string "\t\n\r\f" consisting of a space, a tab, a carriage return and a newline for tokenization. There are two other constructors for class StringTokenizer. In the version that takes two String arguments, the second String is the delimiter string. In the version that takes three arguments, the second String is the delimiter string and the third argument (a boolean) determines whether the delimiters are also returned as tokens (only if the argument is TRue). This is useful if you need to know what the delimiters are.
Line 19 uses StringTokenizer method countTokens to determine the number of tokens in the string to be tokenized. The condition in the while statement at lines 2122 uses StringTokenizer method hasMoreTokens to determine whether there are more tokens in the string being tokenized. If so, line 22 prints the next token in the String. The next token is obtained with a call to StringTokenizer method nextToken, which returns a String. The token is output using println, so subsequent tokens appear on separate lines.
[Page 1378]
If you would like to change the delimiter string while tokenizing a string, you may do so by specifying a new delimiter string in a nextToken call as follows:
tokens.nextToken( newDelimiterString );
This feature is not demonstrated in Fig. 29.18.
18// validate address
19public static boolean validateAddress( String address )
20{
21return address.matches(
22"\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" );
23} // end method validateAddress
24
25// validate city
26public static boolean validateCity( String city )
27{
28return city.matches( "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" );
29} // end method validateCity
30
31// validate state
32public static boolean validateState( String state )
33{
34return state.matches( "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" );
35} // end method validateState
36
37// validate zip
38public static boolean validateZip( String zip )
39{
40return zip.matches( "\\d{5}" );
41} // end method validateZip
42
43// validate phone
44public static boolean validatePhone( String phone )
45{
46return phone.matches( "[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}" );
47} // end method validatePhone
48} // end class ValidateInput
Figure 29.21. Inputs and validates data from user using the ValidateInput class.
(This item is displayed on pages 1381 - 1382 in the print version)
1 |
// |
Fig. 29.21: Validate.java |
2 |
// |
Validate user information using regular expressions. |
3 |
import java.util.Scanner; |
|
4 |
|
|
5public class Validate
6{
7 public static void main( String[] args )
8{
9// get user input
10Scanner scanner = new Scanner( System.in );
11System.out.println( "Please enter first name:" );
12String firstName = scanner.nextLine();
13System.out.println( "Please enter last name:" );
14String lastName = scanner.nextLine();
15System.out.println( "Please enter address:" );
16String address = scanner.nextLine();
17System.out.println( "Please enter city:" );
18String city = scanner.nextLine();
19System.out.println( "Please enter state:" );
20String state = scanner.nextLine();
21System.out.println( "Please enter zip:" );
22String zip = scanner.nextLine();
23System.out.println( "Please enter phone:" );
24String phone = scanner.nextLine();
25
26// validate user input and display error message
27System.out.println( "\nValidate Result:" );
28
29if ( !ValidateInput.validateFirstName( firstName ) )
30System.out.println( "Invalid first name" );
31else if ( !ValidateInput.validateLastName( lastName ) )
32System.out.println( "Invalid last name" );
33else if ( !ValidateInput.validateAddress( address ) )
34System.out.println( "Invalid address" );
35else if ( !ValidateInput.validateCity( city ) )
36System.out.println( "Invalid city" );
37else if ( !ValidateInput.validateState( state ) )
38System.out.println( "Invalid state" );
39else if ( !ValidateInput.validateZip( zip ) )
40System.out.println( "Invalid zip code" );
41else if ( !ValidateInput.validatePhone( phone ) )
42System.out.println( "Invalid phone number" );
43else
44System.out.println( "Valid input. Thank you." );
45} // end main
46} // end class Validate
Please |
enter |
first |
name: |
Jane |
|
|
|
Please |
enter |
last |
name: |
Doe |
|
|
|
Please |
enter |
address: |
|
123 Some Street |
|
||
Please |
enter |
city: |
|
Some City |
|
|
|
Please |
enter |
state: |
|
SS |
|
|
|
Please |
enter |
zip: |
|
123 |
|
|
|
Please |
enter |
phone: |
|
123-456-7890 |
|
|
|
Validate Result: |
|
||
Invalid |
zip |
code |
|
|
|
|
|
Please |
enter |
first |
name: |
Jane |
|
|
|
Please |
enter |
last |
name: |
Doe |
|
|
|
Please |
enter |
address: |
|
123 Some Street |
|
||
Please |
enter |
city: |
|
Some City |
|
|
|
Please |
enter |
state: |
|
SS |
|
|
|
Please |
enter |
zip: |
|
12345 |
|
|
|
Please |
enter |
phone: |
|
123-456-7890 |
|
|
|
Validate Result: |
|
||
Valid |
input. Thank |
you. |
|
|
|
|
|
Figure 29.20 validates user input. Line 9 validates the first name. To match a set of characters that does not have a predefined character class, use square brackets, []. For example, the pattern "[aeiou]" matches a single character that is a vowel. Ranges of characters can be represented by placing a dash (-) between two characters. In the example, "[A-Z]" matches a single uppercase letter. If the first character in the brackets is "^", the expression accepts any character other than those indicated. However, it is important to note that "[^Z]" is not the same as "[A-Y]", which matches uppercase letters AY"[^Z]" matches any character other than capital Z, including lowercase letters and non-letters such as the newline
(?), the quantifier becomes reluctant (sometimes called lazy). It then will match as few occurrences as possible as long as the match is still successful.
The zip code (line 40 in Fig. 29.20) matches a digit five times. This regular expression uses the digit character class and a quantifier with the digit 5 between braces. The phone number (line 46 in Fig. 29.20) matches three digits (the first one cannot be zero) followed by a dash followed by three more digits (again the first one cannot be zero) followed by four more digits.
String Method matches checks whether an entire string conforms to a regular expression. For example, we want to accept "Smith" as a last name, but not "9@Smith#". If only a substring matches the regular expression, method matches returns false.
Replacing Substrings and Splitting Strings
Sometimes it is useful to replace parts of a string or to split a string into pieces. For this purpose, class String provides methods replaceAll, replaceFirst and split. These methods are demonstrated in Fig. 29.23.
Figure 29.23. Methods replaceFirst, replaceAll and split.
(This item is displayed on pages 1384 - 1385 in the print version)
1 |
// |
Fig. 29.23: RegexSubstitution.java |
2 |
// |
Using methods replaceFirst, replaceAll and split. |
3 |
|
|
4public class RegexSubstitution
5{
6 |
public static void main( String |
args[] |
) |
|
|
7 |
{ |
|
|
|
|
8 |
String firstString = "This sentence |
ends in 5 |
stars *****"; |
||
9 |
String secondString |
= "1, 2, |
3, 4, |
5, 6, 7, 8"; |
|
10 |
|
|
|
|
|
11 |
System.out.printf( |
"Original |
String |
1: %s\n", |
firstString ); |
12 |
|
|
|
|
|
13// replace '*' with '^'
14firstString = firstString.replaceAll( "\\*" , "^" );
16System.out.printf( "^ substituted for *: %s\n", firstString );
18// replace 'stars' with 'carets'
19firstString = firstString.replaceAll( "stars", "carets" );
21System.out.printf(
22"\"carets\" substituted for \"stars\": %s\n", firstString );
24// replace words with 'word'
25System.out.printf( "Every word replaced by \"word\": %s\n\n",
26 |
firstString.replaceAll( "\\w+", |
"word" ) ); |
|
||
27 |
|
|
|
|
|
28 |
System.out.printf( "Original String |
2: %s\n", |
secondString |
); |
|
29 |
|
|
|
|
|
30 |
// replace first three digits with 'digit' |
|
|
||
31 |
for ( int i = 0 |
; i < 3; i++ ) |
|
|
|
32 |
secondString |
= secondString.replaceFirst( |
"\\d", "digit" |
); |
|
33 |
|
|
|
|
|
34System.out.printf(
35"First 3 digits replaced by \"digit\" : %s\n", secondString );
36String output = "String split at commas: [" ;
37 |
|
|
|
|
|
38 |
String[] |
results = |
secondString.split( |
",\\s*" |
); // split on commas |
39 |
|
|
|
|
|
40 |
for ( String string : results ) |
|
|
||
41 |
output |
+= "\"" |
+ string + "\", "; |
// output |
results |
42 |
|
|
|
|
|
43// remove the extra comma and add a bracket
44output = output.substring( 0, output.length() - 2 ) + "]";
45System.out.println( output );
46} // end main
47} // end class RegexSubstitution
