hoshicchi hoshicchi - 1 year ago 70
Java Question

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)) {

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



Thanks a bunch for the help!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download