• Tidak ada hasil yang ditemukan

Character

Dalam dokumen Java with BlueJ (Halaman 135-143)

136

Example 1

If the data you have is a string then the String method charAt(...) can be used to access a character at a specific index. When used in conjunction with a for statement the characters of a string can be accessed one-by-one. In the following program we access the characters of a string one-by-one and determine the type of each character using the Character methods isDigit() and isLetter().

Listing 5.3: Types of characters.

1 import java.util.Scanner;

2 /**

3 * A string provided by the user is examined 4 * character by character to determine its type.

5 */

6 public class CharacterTypes

7 {

8 public static void main(String[] args) 9 {

10 Scanner kb = new Scanner(System.in);

11 System.out.print("Enter a line: ");

12 String line = kb.nextLine();

13 // characters are examined one-by-one 14 for (int i = 0; i < line.length(); i++){

15 char c = line.charAt(i);

16 if(Character.isLetter(c))

17 System.out.println(i+"\t"+ c+"\t\tletter");

18 else if(Character.isDigit(c))

19 System.out.println(i+"\t"+c+"\t\tdigit");

20 else

21 System.out.println(i+"\t"+c+"\t\tother");

22 } 23 }

24 }

Below is the output from CharacterTypes.java for when the user provides the string

"A$12"

137

138

Example 2

The Character method getNumericValue() can be used to obtain the decimal value of a character. Consider the program in Listing 5.4. The main method in lines 7-13:

 obtains a line of text from the end user

 calls a method named addDigits to get the sum of digits in the line The addDigits method in lines 15-25

 accesses characters one-by-one.

 In line 21 the getNumericValue() method is used.

Listing 5.4: Types of characters.

1 import java.util.Scanner;

2 /**

3 * The sum of numeric characters is calculated.

4 */

5 public class SumNumericValues

6 {

7 public static void main(String[] args) { 8 Scanner kb = new Scanner(System.in);

9 System.out.print("\nEnter a line: ");

10 String line = kb.nextLine();

11 int sum = addDigits(line);

12 System.out.println("sum = \t"+sum);

13 } 14

15 public static int addDigits(String s){

16 int sum = 0;

17 // characters are examined one-by-one 18 for (int i = 0; i < s.length(); i++){

19 char c = s.charAt(i);

20 if(Character.isDigit(c)){

21 sum += Character.getNumericValue(c);

22 } 23 }

24 return sum;

25 }

139

26 }

Below is the output where the user provides the string "1A 4c!6" .

140

Example 3

In many situations a user’s input must be validated. Suppose a user is prompted for a student number that must comprise only digits. If the user enters invalid characters, and the program executes the Scanner method nextInt(), then the program would crash.

Instead the programmer must use the Scanner method nextInt() and then analyze the characters to determine if the user entered a correctly formatted value.

isDigit(...)can be used to check if a character is a digit or not. Consider Listing 5.5.

Listing 5.5: Validation of input.

1 import java.util.Scanner;

2 /**

3 * A string provided by the user is examined 4 * to determine whether or not it is numeric.

5 */

6 public class ValidateStudentNumber

7 {

8 public static void main(String[] args) 9 {

10 Scanner kb = new Scanner(System.in);

11 System.out.println("Enter a number: ");

12 String number = kb.next();

13 // characters are examined one-by-one 14 boolean valid = true;

15 for (int i = 0; i < number.length(); i++){

16 char c = number.charAt(i);

17 If ( ! Character.isDigit(c)) valid = false;

18 }

19 if (valid) System.out.println("Valid");

20 else System.out.println("Invalid");

21 }

Output from ValidateStudentNumber.java for two runs of the program is shown below.

141 Exercises

5. Java allows char values to be used directly in arithmetic expressions. Modify Example 2 to just add characters instead of the character’s numerical value using a statement such as sum += c; The sum in this case is the sum of the internal representations of those characters.

6. Modify Example 3 so it stops examining characters if it encounters a non-numeric character. Consider using a for that begins: for (int i=0; valid && i<number.length();

i++)

7. Write a program to validate a phone number where the number is expected to be a string of 10 digits. For example if the user entered 2343214567 the number would be valid, but if the user entered ADG3214567 the number would be invalid.

8. The standard US zip code is five digits. Write a program that prompts the user for a zip code and then determines if it is valid or not. To be valid the code must be five characters in length and all characters must be digits.

9. In 1983 the US Postal Service extended zip codes (ZIP+4) to include the five digits of the ZIP code, a hyphen, and four more digits that determine a more specific location within a given ZIP code. Write a program to validate a zip code entered by the user where the user might have entered a standard zip code (5 characters) or a zip+4 code (10 characters including the dash separating the first 5 digits from the last 4 digits).

10. Sweden has a personal identity number (personnummer) that is issued by the Swedish Tax Agency. This identity number has 10 digits with a hyphen between the 6th and 7th digits, and is such that the 10th digit is a check digit. The check digit is calculated using the first 9 digits. A weighted sum of products is calculated as P(digiti × weighti) where the weights are 2, 1, 2, 1, 2, 1, 2, 1, 2. However if a product is more than 9 it is replaced by the sum of its digits. The check digit must be equal to 10 minus the last digit (but note that if the last digit of the sum is zero, the check digit is 0). Write a program to verify the user has entered a valid personnummer:

• 10 digits with a dash between the 6th and 7th digits, and

• the check digit is correctly based on the first 9 digits.

For example consider the personnummer 811228-9874. To verify the check digit (the last digit, the 4) is correct we need to follow the above procedure. The sum of the weighted products is:

142

(8×2)+(1×1)+(1×2)+(2×1)+(2×2)+(8×1)+(9×2)+(8×1)+(7×2) which are:

(16) + 1 + 2 + 2 + 4 + 8 + (18) + 8 + (14) and modifying where the product > 9:

(1 + 6) + 1 + 2 + 2 + 4 + 8 + (1 + 8) + 8 + (1 + 4) we have:

7 + 1 + 2 + 2 + 4 + 8 + 9 + 8 + 5 = 46

And finally 10 − 6 = 4. So, the personnummer above is valid.

143

Dalam dokumen Java with BlueJ (Halaman 135-143)

Dokumen terkait