我正在编写一个程序来计算每个单词的长度,然后计算该长度出现的次数。
例如:
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.
任何建议如何解决这个问题或任何其他更简单的方法来做到这一点(不使用集合, map )。
最佳答案
您可以替换 array
与 Map<Integer,Integer>
,这会很容易。
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String :");
String s = sc.nextLine();
String[] arr = s.split(" ");// get the words
Map<Integer, Integer> lengthVsCount=new HashMap<>(); // length vs count
for(String i:arr){ // iterate array
Integer val=lengthVsCount.get(i.length()); // searching count
if(val!=null){ // if count is there
lengthVsCount.put(i.length(),val+1);// increment count by one
}else{ // count not there
lengthVsCount.put(i.length(),1); // add count as one
}
}
for (Map.Entry<Integer,Integer> entry:lengthVsCount.entrySet()) {
System.out.println("No. of words of length " + entry.getKey() + " are " + entry.getValue() + ".");
}
关于java - 计算出现次数的单词长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27564936/