欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

第六章第二十题(计算一个字符串中字母的个数)(Count the letters in a string) - 编程练习题答案

程序员文章站 2024-01-17 10:16:34
6.20(计算一个字符串中字母的个数)编写一个方法,使用下面的方法头计算字符串中的字母个数: public static int countLetters(String s) 编写一个测试程序,提示用户输入字符串,然后显示字符串中的字母个数。 6.20(Count the letters in a ......

*6.20(计算一个字符串中字母的个数)编写一个方法,使用下面的方法头计算字符串中的字母个数:
public static int countletters(string s)

编写一个测试程序,提示用户输入字符串,然后显示字符串中的字母个数。
*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.

下面是参考答案代码:

import java.util.scanner;

public class ans6_20_page201 {
    public static void main(string[] args) {
        scanner input = new scanner(system.in);
        system.out.print("enter : ");
        string s = input.nextline();
        system.out.println("the number of letters is "+ countletters(s));
    }
    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;
    }
}

适用java语言程序设计与数据结构(基础篇)(原书第11版)java语言程序设计(基础篇)(原书第10/11版)