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']++;}可以實現對字符的計數,沒能理解。哪位大神能說明一下麼。書上解釋沒看懂。
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,等等。
所以讓對應下標++實現了對這個字母的計數。