Ignore Non-Letter Characters
In the previous step, we saw that Character.isUpperCase()
returns false
for characters that are not letters, such as spaces and numbers. Often, when analyzing text, we are only interested in the letters and want to ignore other characters.
The Character
class provides another useful method, Character.isLetter()
, which returns true
if a character is a letter (either uppercase or lowercase), and false
otherwise. We can combine Character.isLetter()
and Character.isUpperCase()
to check if a character is an uppercase letter and ignore non-letter characters.
Let's modify our program to count the number of uppercase letters in the string, ignoring spaces, numbers, and other non-letter characters.
-
Open the HelloJava.java
file in the WebIDE editor.
-
Replace the existing code with the following:
public class HelloJava {
public static void main(String[] args) {
String testString = "Hello Java 123";
int uppercaseCount = 0;
System.out.println("Counting uppercase letters in the string: \"" + testString + "\"");
for (int i = 0; i < testString.length(); i++) {
char currentChar = testString.charAt(i);
// Check if the character is a letter AND if it is uppercase
if (Character.isLetter(currentChar) && Character.isUpperCase(currentChar)) {
uppercaseCount++;
System.out.println("Found uppercase letter: '" + currentChar + "' at index " + i);
}
}
System.out.println("Total uppercase letters found: " + uppercaseCount);
}
}
In this code:
- We initialize an integer variable
uppercaseCount
to 0.
- Inside the loop, we add an
if
condition: if (Character.isLetter(currentChar) && Character.isUpperCase(currentChar))
. The &&
operator means "and". This condition is true only if both Character.isLetter(currentChar)
is true and Character.isUpperCase(currentChar)
is true.
- If the condition is true, we increment
uppercaseCount
and print a message indicating that an uppercase letter was found.
- After the loop finishes, we print the total count of uppercase letters.
-
Save the file (Ctrl+S or Cmd+S).
-
Compile the program in the Terminal:
javac HelloJava.java
-
Run the compiled program:
java HelloJava
You should see output similar to this:
Counting uppercase letters in the string: "Hello Java 123"
Found uppercase letter: 'H' at index 0
Found uppercase letter: 'J' at index 6
Total uppercase letters found: 2
This output shows that our program correctly identified and counted only the uppercase letters ('H' and 'J'), ignoring the lowercase letters, spaces, and numbers.