What is RandomCharacter.getRandomLowerCaseLetter() ?????

  今天在看书顺便打打书上的代码时,看到这么一个方法的调用RandomCharacter.getRandomLowerCaseLetter()!

  年轻的我看到这一大串单词时还以为是JDK自带类里面方法Orz,写上去cmd+b一跑,果不其然报错

CountLettersInArray.java:22: 错误: 找不到符号
            chars[i] = RandomCharacter.getRandomLowerCaseLetter();        //自定义类
                       ^
  符号:   变量 RandomCharacter
  位置: 类 CountLettersInArray
1 个错误

先奉上书上源代码先

 1 //随机生成100个小写字母保存在一个数组中,然后统计它们出现的次数,显示
 2 
 3 public class CountLettersInArray{
 4     public static void main(String args[]){
 5         char[] chars = creatArray();
 6 
 7         System.out.println("The lower case is:");
 8         displayArray(chars);
 9 
10         int[] counts = countLetters(chars);
11 
12         System.out.println();
13         System.out.println("The occurences of each letter are:");
14         displayCounts(counts);
15     }
16 
17     public static char[] creatArray(){            //创建100个随机小写字母
18 
19         char[] chars = new char[100];
20 
21         for (int i = 0; i < chars.length; i++)
22             chars[i] = RandomCharacter.getRandomLowerCaseLetter();        //自定义类
23 
24         return chars;
25     }
26 
27     public static void displayArray(char[] chars){        //显示随机字母的数组
28         for(int i = 0; i < chars.length; i++){
29             if ((i + 1) % 20 == 0)
30                 System.out.println(chars[i]);
31             else
32                 System.out.print(chars[i] + " ");
33         }
34     }
35 
36     public static int[] countLetters(char[] chars){                //计算数量
37         int[] counts = new int[26];
38 
39         for(int i = 0; i < chars.length; i++)
40             counts[chars[i] - 'a']++;
41 
42         return counts;
43     }
44 
45     public static void displayCounts(int[] counts){                //显示统计数量后的数组
46         for (int i = 0; i < counts.length; i++){
47             if ((i + 1) % 10 == 0)
48                 System.out.println(counts[i] + " " + (char)(i + 'a'));
49             else
50                 System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
51         }
52     }
53 
54 
55 }

随后百度一下,果然还是有同学跟我一样情况23333。

果然还是自定义类嘛怎么可能会有那么长的自带方法233。

奉上解决方法

public class RandomCharacter {

    //生成一个介于ch1 和 ch2 的随机字母

    public static char getRandomCharacter(char ch1, char ch2) {

        return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    //生成一个随机的小写字母

    public static char getRandomLowerCaseLetter() {

        return getRandomCharacter('a', 'z');

    }

}

 

原文地址:https://www.cnblogs.com/liangjiahao713/p/6498085.html