Chapter 6 Question 20 (Count the letters in a string)

Chapter 6 Question 20 (Count the letters in a string)

  • *6.20 (Count the number of letters in a string) Write a method, use the following method header to count the number of letters in a string:
    public static int countLetters(String s)
    Write a test program that prompts the user to enter a string, Then display the number of letters in the string.
    *6.20(Count the letters in a string) Write a method that counts the number of letters in a string using the following header:
    public static int countLetters(String s)
    Write a test program that prompts the user to enter a string and displays the number of letters in the string.
  • Reference Code:
package chapter06;

import java.util.Scanner;

public class Code_20 {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();
        System.out.println("The number of the string is " + countLetters(str));
    }
    public static int countLetters(String s){
    
    
        int count = 0;
        for (int i = 0;i < s.length();i++){
    
    
            if (Character.isLetter(s.charAt(i)))
                count++;
        }
        return count;
    }
}

  • The results show that:
Enter a string: jxh1025?
The number of the string is 3

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/jxh1025_/article/details/109165848