The problem
Write a program that prompts the user to enter a string and displays the number of the uppercase letters in the string.
Breaking it down
First calling the string.chars()
which will return a IntStream
. Using java 8 we can capture the number of upper case letters by using a predicate Character::isUpperCase
and passing it to the filter method. Finally we will use the stream terminal operation count to find the total number of instances.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string: ");
String inputString = input.nextLine();
input.close();
long count = inputString.chars().filter(Character::isUpperCase).count();
System.out.println("The number of uppercase letters is " + count);
}
Output
Enter a string:
A is Coming Down the road
The number of uppercase letters is 3