アルテミスハンター:
問題
私は、それぞれの文字は、ユーザーが文字列入力に現れる回数をチェックするためにこのプログラムを書きました。それは罰金を動作しますが、一つ一つの文字の二十から六要素-long配列によって反復するよりも、このタスクについて行くのより効率的または代替ソリューションはありますか?
コード
import java.util.Scanner;
public class Letters {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
System.out.println("Enter a string.");
String k = sc.nextLine();
String s = k.toUpperCase();
s = s.trim();
int l = s.length();
System.out.println("Checking string = " + s);
char ch;
for (int i = 0; i < l; i++) {
ch = s.charAt(i);
for (int j = 0; j < c.length; j++) {
if (ch == c[j]) {
f[j]++;
}
}
}
System.out.println("Char\tFreq");
for (int i = 0; i < c.length; i++) {
if (f[i] != 0) {
System.out.println(c[i] + "\t" + f[i]);
}
}
}
}
エリオットの新鮮:
明示的に(デフォルト値はゼロである)あなたの周波数配列に26個のエントリを初期化するには必要はありません。あなたも(オフセットを知るのに十分である)文字のテーブルを維持する必要はありません。それはあなたのコードを排除することができ、あるc
完全かつ各文字を計算します。お気に入り、
Scanner sc = new Scanner(System.in);
int[] f = new int[26];
System.out.println("Enter a string.");
String orig = sc.nextLine();
String k = orig.trim().toUpperCase();
System.out.println("Checking string = " + orig);
for (char ch : k.toCharArray()) {
f[ch - 'A']++;
}
System.out.println("Char\tFreq");
for (int i = 0; i < f.length; i++) {
if (f[i] != 0) {
System.out.println((char) ('A' + i) + "\t" + f[i]);
}
}