我應該要求用戶輸入一個字符串,我應該解析字符串並跟蹤字母表的數量。所以像,如果用戶輸入字符串「ABEE」 它顯示輸出:JAVA - 存儲字符串和字符串的數量
a: 1
b: 1
c: 0
e: 2
到目前爲止,我已經能夠得到字符串並解析它並保存元素到數組。而且我一次可以用for循環打印出每封信。現在我面臨的問題是,當它打印出字母以及短語中存在多少字母時,這些數字不匹配。例如,如果我輸入字母:「abccddee」 它打印出:
a: 1
b: 1
c: 1
c: 0
d: 0
d: 0
e: 0
e: 0
出於測試目的,我用我自己的字符串,而不是使用掃描儀。
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
//create arrays
String[] upper = new String[25];
String[] lowerChar = new String[25];
int [] lowerCharNum = new int[25];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the size of the phrase entered from user
String[] letters = new String[phrase.length()];
System.out.println("letters length: " + letters.length);
//separate every letter in phrase and store it into array "letters"
letters = phrase.split("");
for(int i=0; i<letters.length; i++)
{
lowerChar[i] = letters[i];
switch(letters[i])
{
case "a":
lowerCharNum[0] += 1;
break;
case "b":
lowerCharNum[1] += 1;
break;
case "c":
lowerCharNum[2] += 1;
break;
case "d":
lowerCharNum[3] += 1;
break;
case "e":
lowerCharNum[4] += 1;
break;
case "f":
lowerCharNum[5] += 1;
break;
}//end of switch
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
}
}//end of main method
}//end of class
你爲什麼要從'String phrase'創建一個單獨的'String'數組? –
因爲分配我必須讓程序解析大寫字母和小寫字母,所以我讓字母數組來保存所有的字母數組,然後將它們分開到相應的upper和lowerChar數組中。 – rissandimo
@rissandimo:請注意,您的方法不能很好地擴展。我建議你閱讀下面發佈的答案。 – Bhoot