好吧,身份證認爲自己知道的基礎知識和一些先進的Java,但仍然沒有勇氣開始編程我的想法,我有。這是一個簡單的程序,我想出了,基本上輸出特定字母的量你的文字已經(我想我的措辭是錯誤的...)這是我的代碼:一個更簡單和有效的方法來做到這一點?
public class gene {
public static void main(String[] args) {
String[] phrases = {"hello", "egg", "learning", "ferrero", "rocher",
"Horologe", "Twinling"};
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;
int f=0;
int g=0;
int h=0;
int i=0;
int j=0;
int k=0;
int l=0;
int m=0;
int n=0;
int o=0;
int p=0;
int q=0;
int r=0;
int s=0;
int t=0;
int u=0;
int v=0;
int w=0;
int x=0;
int y=0;
int z=0;
for(int ii =0; ii <phrases.length; ii++){
char[] charphrases = phrases[ii].toCharArray();
for(int iii = 0; iii<charphrases.length; iii++){
switch(charphrases[iii]){
case ('a'):
a++;
break;
case ('b'):
b++;
break;
case ('c'):
c++;
break;
case ('d'):
d++;
break;
case ('e'):
e++;
break;
case ('f'):
f++;
break;
case ('g'):
g++;
break;
case ('h'):
h++;
break;
case ('i'):
i++;
break;
case ('j'):
j++;
break;
case ('k'):
k++;
break;
case ('l'):
l++;
break;
case ('m'):
m++;
break;
case ('n'):
n++;
break;
case ('o'):
o++;
break;
case ('p'):
p++;
break;
case ('q'):
q++;
break;
case ('r'):
r++;
break;
case ('s'):
s++;
break;
case ('t'):
t++;
break;
case ('u'):
u++;
break;
case ('v'):
v++;
break;
case ('w'):
w++;
break;
case ('x'):
x++;
break;
case ('y'):
y++;
break;
case ('z'):
z++;
break;
}
}
}
System.out.println("A:" + a + "\n" + "B:" + b + "\n" +"C:" + c + "\n" +"D:" + d + "\n" +"E:" + e + "\n" +"F:" + f + "\n" +"G:" + g + "\n" +"H:" + h + "\n" +"I:" + i+ "\n" +"J:" + j + "\n" +"K:" + k + "\n" +"L:" + l + "\n" +"M:" + m + "\n" +"N:" + n + "\n" +"O:" + o + "\n" +"P:" + p + "\n" +"Q:" + q + "\n" +"R:" + r+ "\n" +"S:" + s + "\n" +"T:" + t + "\n" +"U:" + u + "\n" +"V:" + v + "\n" +"W:" + w + "\n" +"X:" + x + "\n" +"Y:" + y + "\n" +"Z:" + z + "\n" + z);
}
}
正如你可以看到,它對於這樣一個簡單的程序非常長,毫無疑問有一個更短的寫法。有人可以告訴我在哪裏可以縮小程序,使其更短,更高效。
請修正你的標題。它應該描述實際問題。 – EJP
瞭解[arrays](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)。你可以用一個數組來代替26個單獨的變量。 – Jesper
不錯的地方可能是[http://codereview.stackexchange.com/](http://codereview.stackexchange.com/)在這裏,你的代碼得到審查。 :) –