Skip to content
Advertisement

How to count count the number of names Java

Hi guys. I’m new to Java, currently learning Strings.

I have a task to count the number of names, the length of the name must be at least two, the first letter of the name should start with upper case, the second with lower case.

The issue is that I don’t know how to use the Character.isUpperCase(text.charAt(i)) and Character.isLowerCase(text.charAt(i + 1)) in the same if.

I would use some advice or hint.

class NameCounterTest {
    public static void main(String[] args) {
        // 1
        System.out.println(new NameCounter().count("Mars is great planet"));

        // 2
        System.out.println(new NameCounter().count("Moon is near Earth"));

        // 0
        System.out.println(new NameCounter().count("SPACE IS GREAT"));
    }
}

class NameCounter {
    public int count(String text) {
        String[] words = text.split(" ");

        int wordLength = 0, counter = 0;

        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            wordLength = word.length();

            if (wordLength >= 2 && Character.isUpperCase(text.charAt(i)))
                counter++;
        }
        return counter;
    }
}

Output:
1; //Should be 1;
1; //Should be 2;
3; //Should be 0;

Advertisement

Answer

You can use word.charAt(0) and word.charAt(1) to get the first and second character in each word in the loop.

class NameCounterTest {
    public static void main(String[] args) {
        // 1
        System.out.println(new NameCounter().count("Mars is great planet"));

        // 2
        System.out.println(new NameCounter().count("Moon is near Earth"));

        // 0
        System.out.println(new NameCounter().count("SPACE IS GREAT"));
    }
}

class NameCounter {
    public int count(String text) {
        String[] words = text.split(" ");

        int wordLength = 0, counter = 0;

        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            wordLength = word.length();

            if (wordLength >= 2 && Character.isUpperCase(word.charAt(0)) && Character.isLowerCase(word.charAt(1)))
                counter++;
        }
        return counter;
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement