java - 计算出现次数的单词长度

标签 java arrays string

我正在编写一个程序来计算每个单词的长度,然后计算该长度出现的次数。

例如:

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 )。

最佳答案

您可以替换 arrayMap<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/

相关文章:

java - 泛型和继承问题

c - 从文件中读取并标记化输入 C

java - 有没有办法在这段代码中避免@SuppressWarnings?

python - 从列表中创建一个新列表但没有重复项?

java - 如何在Eclipse ADT中打开Android源代码

java - 在没有中间类的情况下将数据插入到 JavaFX TableView

java - jvisualvm 线程 cpu 时间使用

php - 如何使用str_split()?

arrays - SWIFT - 无法将类型 '[(String, [String : Any])]' 的值分配给类型 '[String : [String : Any]]'

php - 查找日期是否超过 30 天