我正在做一個程序來計算每個字的長度,然後是該長度出現的次數。計算出現的字長度
例如:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
到目前爲止,我想這一點,
import java.util.Scanner;
class Demo{
public static void main(String[] args){
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
s=sc.nextLine();
String[] arr = s.split(" ");
String str = "";
int [] len = new int[arr.length];
int [] count = new int[arr.length];
int c = 0;
for(int i=0;i<arr.length;i++){
str = arr[i];
len[i] = str.length();
for(int j=0;j<arr.length;j++){
if(str.length() == arr[j].length()){
count[i] = ++c;
}
}
c = 0;
}
for(int i=0;i<len.length;i++){
System.out.println("No. of words of length "+len[i]+" are "+count[i]+".");
}
}
}
有一個在我的邏輯存在問題,這就是爲什麼它的輸出是這樣的:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
No. of words of length 4 are 2.
任何建議如何解決這個問題或任何其他更簡單的方法來做到這一點(不使用集合,地圖)。
首先你應該考慮使用HashMap來存放計數器。地圖<「您計數的數字」,「發生次數」>是解決問題的標準方法。 – 2014-12-19 11:20:01
您將爲每個相同長度的字獲得冗餘輸出。如Marcin指出的那樣使用Map。 – 2014-12-19 11:22:05