hoshicchi
hoshicchi

Reputation: 77

Counting a String's Lowercase Letters

I was looking around forums and found a helpful code on how to count lowercase letters in an inputted string. Thing is, after testing it, I saw it only counts lowercase letters within the first word typed. So, for example, if I type: HeRE the counter will say I've typed in 1 lowercase letter (which is correct), but if I type in: HeRE i am the counter will still only say 1 instead of 4. It's only counting the lowercase letters in the first word. How do I get it to count lowercase letters in my entire string?

Code thus far:

 import java.util.Scanner;
 public class countingLowerCaseStrings {
 public static void main(String args[]){
 Scanner scanner = new Scanner(System.in);

 System.out.println("Enter your string: ");
 String input = scanner.next();

 int LowerCaseLetterCounter = 0;
   for (char ch : input.toCharArray()) {
     if (Character.isLowerCase(ch)) {
     LowerCaseLetterCounter++;
  }
}

   System.out.println ("Number of lower case letters in this string is: " +
   LowerCaseLetterCounter);

   }

  }

Thanks a bunch for the help!

Upvotes: 1

Views: 953

Answers (2)

sprinter
sprinter

Reputation: 27956

As a matter of interest, Java 8 provides a fairly streamlined way of achieving the same thing:

scanner.nextLine().chars().filter(Character::isLowerCase).count()

Upvotes: 0

BackSlash
BackSlash

Reputation: 22233

scanner.next(); reads the first available word, not the entire line.

So if you input "HeRE i am" it will just read "HeRE".

Change it to scanner.nextLine():

System.out.println("Enter your string: ");
String input = scanner.nextLine();

DEMO - look at stdin and stdout panels.

Upvotes: 3

Related Questions