qazqzad 2016-02-26 17:57 采纳率: 100%
浏览 1596
已采纳

关于java se 的小问题

java语言程序设计第7章程序清单7-4

package Program7;

import Program6.Program6_10GetCharacter;

public class Program7_4 {

    public static void main(String[] args) {
        char[] chars = createArray();

        System.out.println("The lowercase letters are: ");
        displayArray(chars);

        int[] counts = countLetters(chars);

        System.out.println();
        System.out.println("The occurrences of each letters are: ");
        displayCounts(counts);

    }

    public static char[] createArray() {
        char[] chars = new char[100];

        for (int i = 0; i < chars.length; i++)
            chars[i] = Program6_10GetCharacter.getRandomLowerCaseLetter();

        return chars;
    }

    public static void displayArray(char[] chars) {
        for (int i = 0; i < chars.length; i++) {
            if((i + 1) % 20 == 0)
                System.out.println(chars[i]);
            else
                System.out.print(chars[i] + " ");
        }
    }

    public static int[] countLetters(char[] chars) {
        int[] counts= new int[26];

        for (int i = 0; i < chars.length; i++) {
            counts[chars[i] - 'a']++;
        }
        return counts;
    }

    public static void displayCounts(int[] counts) {
        for (int i = 0; i < counts.length; i++) {
            if((i + 1) % 10 == 0)
                System.out.println(counts[i] + " " + (char)(i + 'a'));
            else
                System.out.print(counts[i] + " " + (char)(i + 'a') + " ");              
        }

    }
}

在 public static int[] countLetters(char[] chars) 方法里,用for (int i = 0; i < chars.length; i++) {counts[chars[i] - 'a']++;}可以实现对字符的计数,没能理解。哪位大神能说明一下么。书上解释没看懂。

  • 写回答

5条回答

  • threenewbee 2016-02-26 22:54
    关注

    int[] counts= new int[26];counts这个数组有26个元素,的0下标存储的是a的个数,1下标存储b的个数,2下标存储c的个数……
    chars[i] - 'a',把这个字符转换成对应的下标,比如chars[i]是'a',那么'a'-'a'=0,如果chars[i]是'b',那么'b'-'a'=1,等等。
    所以让对应下标++实现了对这个字母的计数。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料