Returns true if the string has exactly one uppercase letter, false otherwise - Java java.lang

Java examples for java.lang:String Case

Description

Returns true if the string has exactly one uppercase letter, false otherwise

Demo Code


//package com.java2s;

public class Main {
    /**//from   ww w.  jav  a 2  s  . com
     * Returns true if the string has exactly one uppercase letter, false otherwise
     * 
     * You'll want to use a recursive helper function
     * 
     * Use Character.isUpperCase to check if a letter is uppercase
     * 
     * Examples:
     * "abc" returns false
     * "aBc" returns true
     * "aBcD" returns false
     * "A" returns true
     * "" returns false
     * 
     * @param input
     * @return true if there is one uppercase character
     */
    public static boolean hasExactlyOneUppercase(String input) {
        return hasExactlyOneUppercaseHelper(input, 0, 0);
    }

    private static boolean hasExactlyOneUppercaseHelper(String input,
            int uppercaseCount, int index) {
        if (index < input.length()) {
            if (uppercaseCount > 1) {
                return false;
            } else if (Character.isUpperCase(input.charAt(index))) {
                return hasExactlyOneUppercaseHelper(input,
                        uppercaseCount + 1, index + 1);
            } else {
                return hasExactlyOneUppercaseHelper(input, uppercaseCount,
                        index + 1);
            }
        } else if (uppercaseCount == 1) {
            return true;
        }
        return false;
    }
}

Related Tutorials