Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

java - How to count uppercase and lowercase letters in a string?

yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains:

output example: the string has 8 uppercase letters the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D!

import java.util.Scanner;
public class q36{
    public static void main(String args[]){

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input=keyboard.nextLine();

        int lengde = input.length();
        System.out.println("String: " + input + " " + "lengde:"+ lengde);

        for(int i=0; i<lengde;i++) {
            if(Character.isUpperCase(CharAt(i))){

            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply create counters that increment when a lowercase or uppercase letter is found, like so:

for (int k = 0; k < input.length(); k++) {
    /**
     * The methods isUpperCase(char ch) and isLowerCase(char ch) of the Character
     * class are static so we use the Class.method() format; the charAt(int index)
     * method of the String class is an instance method, so the instance, which,
     * in this case, is the variable `input`, needs to be used to call the method.
     **/
    // Check for uppercase letters.
    if (Character.isUpperCase(input.charAt(k))) upperCase++;

    // Check for lowercase letters.
    if (Character.isLowerCase(input.charAt(k))) lowerCase++;
}

System.out.printf("There are %d uppercase letters and %d lowercase letters.",upperCase,lowerCase);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...