Characters |
There is clearly a relationship between strings and characters, so it makes sense that we take a moment to think a bit about characters.
A character is what we might imagine roughly speaking, it is a keyboard character. This includes special function characters (like newline and tab), in addition to alphanumeric characters.
A character is represented internally as a number an integer, in fact. There are various "universal" codes that can be used to represent chars:
To declare a variable to be of character type:
private char letter;
Use single quotes for character constants: 'H' is a char; "H" is a String:
char letter = 'H';
A String method allows one to extract a character from a string:
public char charAt(int index) // Returns the character at the specified index.
Demo 4. Using charAt and information about characters to fix the color mixer demo from weeks ago. See the color mixer demo. Notice how it behaves if you include a non-digit in the input.
Will step through the string character by character, checking each to be sure it's in the range '0' to '9'. Can do this because the characters are compared according to their code values, and their code values are consecutive.
// Checks whether a given string can be interpreted as an integer: i.e., // checks that it is made up of characters that are digits in the range // 0-9. Returns true if and only if the string can be interpreted as // an integer. private boolean isInteger(String aString) { boolean allNumeric = true; for (int i = 0; (i < aString.length() && allNumeric); i++) { if (aString.charAt(i) < '0' || aString.charAt(i) > '9') allNumeric = false; } return allNumeric; }
Alternatively, we could write the slightly more compact version:
// Checks whether a given string can be interpreted as an integer: i.e., // checks that it is made up of characters that are digits in the range // 0-9. Returns true if and only if the string can be interpreted as // an integer. private boolean isInteger(String aString) { for (int i = 0; (i < aString.length()); i++) { if (aString.charAt(i) < '0' || aString.charAt(i) > '9') return false; } return true; }
Notice that this version will return faster if there is a non-digit in the input.
Characters |