我正在做一个程序来计算每个字的长度,然后是该长度出现的次数。计算出现的字长度
例如:
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