public class CapitalizationChecker {
public static boolean verifyAllUpperOrAllLowerOrIsCapitalized(String word) {
int upper = 0;
int lower = 0;
for (char ch : word.toCharArray()) {
if (Character.isLowerCase(ch)) {
lower++;
} else if (Character.isUpperCase(ch)) {
upper++;
}
}
// All lowercase
if (upper == 0) return true;
// All uppercase
if (lower == 0) return true;
// Only the first letter is uppercase
if (upper == 1 && Character.isUpperCase(word.charAt(0))) return true;
// Otherwise, invalid capitalization
return false;
}
/**
* Runs a test on a given word and prints the result.
*/
public static void runTest(String word) {
System.out.println("Testing word: \"" + word + "\"");
if (verifyAllUpperOrAllLowerOrIsCapitalized(word)) {
System.out.println("OK");
} else {
System.out.println("Error");
}
System.out.println();
}
public static void main(String[] args) {
runTest("PROGRAMMING");
runTest("programming");
runTest("Programming");
runTest("ProGramMing");
}
}
/*
run:
Testing word: "PROGRAMMING"
OK
Testing word: "programming"
OK
Testing word: "Programming"
OK
Testing word: "ProGramMing"
Error
*/